コード例 #1
0
        protected override void OnUpdate()
        {
            EndSimulationEntityCommandBufferSystem endSimECBSystem = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>();

            EntityCommandBuffer.ParallelWriter parallelWriter = endSimECBSystem.CreateCommandBuffer().AsParallelWriter();
            Random random = new Random((uint)Environment.TickCount);

            Entities.ForEach((Entity entity, int entityInQueryIndex, in StressTestCommand cmd) =>
            {
                for (int i = 0; i < cmd.Count; i++)
                {
                    Entity obj = parallelWriter.Instantiate(entityInQueryIndex, cmd.Prefab);

                    float3 moveStart      = random.NextFloat3Direction() * cmd.StartMoveRadius;
                    float3 moveEnd        = random.NextFloat3Direction() * cmd.EndMoveRadius;
                    EaseDesc moveEaseDesc = new EaseDesc(cmd.MoveEaseType, cmd.MoveEaseExponent);
                    Tween.Move(parallelWriter, entityInQueryIndex, obj, moveStart, moveEnd, cmd.MoveDuration, moveEaseDesc, cmd.MoveIsPingPong, cmd.MoveLoopCount);

                    quaternion rotateEnd    = quaternion.AxisAngle(random.NextFloat3Direction(), random.NextFloat(cmd.MinRotateDegree, cmd.MaxRotateDegree));
                    EaseDesc rotateEaseDesc = new EaseDesc(cmd.RotateEaseType, cmd.RotateEaseExponent);
                    Tween.Rotate(parallelWriter, entityInQueryIndex, obj, quaternion.identity, rotateEnd, cmd.RotateDuration, rotateEaseDesc, cmd.RotateIsPingPong, cmd.RotateLoopCount);

                    float3 scaleStart      = new float3(random.NextFloat(cmd.MinStartScale, cmd.MaxStartScale));
                    float3 scaleEnd        = new float3(random.NextFloat(cmd.MinEndScale, cmd.MaxEndScale));
                    EaseDesc scaleEaseDesc = new EaseDesc(cmd.ScaleEaseType, cmd.ScaleEaseExponent);
                    Tween.Scale(parallelWriter, entityInQueryIndex, obj, scaleStart, scaleEnd, cmd.ScaleDuration, scaleEaseDesc, cmd.ScaleIsPingPong, cmd.ScaleLoopCount);
                }

                parallelWriter.RemoveComponent <StressTestCommand>(entityInQueryIndex, entity);
            }).ScheduleParallel();

            endSimECBSystem.AddJobHandleForProducer(Dependency);
        }
コード例 #2
0
    public void AddRock(float3 pos_world)
    {
        var ep = new ParticleSystem.EmitParams {
            position          = pos_world,
            velocity          = rand.NextFloat3Direction() * rand.NextFloat(.5f, 3f),
            rotation3D        = ((Quaternion)rand.NextQuaternionRotation()).eulerAngles,
            angularVelocity3D = Quaternion.AngleAxis(rand.NextFloat(-.2f, 2f), rand.NextFloat3Direction()).eulerAngles,
        };

        Particles.Emit(ep, 1);
    }
コード例 #3
0
        void Start()
        {
            var manager   = World.Active.GetOrCreateManager <EntityManager>();
            var archetype = manager.CreateArchetype(
                typeof(Position),
                typeof(Rotation),
                typeof(Scale),
                typeof(Velocity),
                typeof(Acceleration),
                typeof(NeighborsEntityBuffer),
                typeof(MeshInstanceRenderer));
            var random = new Unity.Mathematics.Random(853);

            for (int i = 0; i < boidCount; ++i)
            {
                var entity = manager.CreateEntity(archetype);
                manager.SetComponentData(entity, new Position {
                    Value = random.NextFloat3(1f)
                });
                manager.SetComponentData(entity, new Rotation {
                    Value = quaternion.identity
                });
                manager.SetComponentData(entity, new Scale {
                    Value = new float3(boidScale.x, boidScale.y, boidScale.z)
                });
                manager.SetComponentData(entity, new Velocity {
                    Value = random.NextFloat3Direction() * param.initSpeed
                });
                manager.SetComponentData(entity, new Acceleration {
                    Value = float3.zero
                });
                manager.SetSharedComponentData(entity, renderer);
            }
        }
コード例 #4
0
    public void Convert(Entity _entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        UnityEngine.Debug.Log("GameObjectConversionSystem");

        TrailRendererSystem.m_Material = m_TrailMat;

        EntityManager manager = dstManager;//World.DefaultGameObjectInjectionWorld.EntityManager;

        EntityArchetype arch   = manager.CreateArchetype(typeof(Translation), typeof(TrailVelocityComponent), typeof(TrailComponent), typeof(TrailBufferElement));
        Random          random = new Random(99);

        for (int i = 0; i < m_ParticleCount; ++i)
        {
            Entity entity = manager.CreateEntity(arch);
            //manager.SetName(entity, "Trail_" + i.ToString());
            manager.SetComponentData(entity, new Translation()
            {
                Value = new float3(1, 1, 1)
            });
            manager.SetComponentData(entity, new TrailVelocityComponent()
            {
                Value = random.NextFloat3Direction()
            });
            manager.SetComponentData(entity, new TrailComponent()
            {
                MeshCount = 20
            });
            DynamicBuffer <TrailBufferElement> buffer = manager.GetBuffer <TrailBufferElement>(entity);
            buffer.Add(new TrailBufferElement(new float3(1, 1, 1)));
        }
    }
コード例 #5
0
        public void GetNextRandomPosition(out float3 pos, out quaternion rot, out float3 forward, out float2 localPos, out float speed, out int2 gridId)
        {
            int find = 0;

            pos      = new float3();
            rot      = new quaternion();
            forward  = new float3();
            gridId   = new int2();
            speed    = 0;
            localPos = new float2();
            float3 min = startPos - Size / 2;
            float3 max = startPos + Size / 2;

            while (find == 0)
            {
                pos    = RandomGen.NextFloat3(min, max);
                gridId = GetGridId(pos);
                if (!IsWalkable(gridId))
                {
                    continue;
                }
                pos.y     = 0;
                forward   = RandomGen.NextFloat3Direction();
                forward.y = 0;
                forward   = math.normalize(forward);
                rot       = quaternion.LookRotation(forward, new float3(0, 1, 0));
                localPos  = GetLocalPos(gridId, pos);
                speed     = RandomGen.NextFloat(1.0f, 2.0f);
                find      = 1;
            }

            return;
        }
コード例 #6
0
    void Start()
    {
        var settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        var prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var random        = new Unity.Mathematics.Random(853);

        for (int i = 0; i < boidCount; ++i)
        {
            var instance = entityManager.Instantiate(prefab);
            var position = transform.TransformPoint(random.NextFloat3(1f));

            entityManager.SetComponentData(instance, new Translation {
                Value = position
            });
            entityManager.SetComponentData(instance, new Rotation {
                Value = quaternion.identity
            });
            entityManager.SetComponentData(instance, new NonUniformScale {
                Value = new float3(boidScale.x, boidScale.y, boidScale.z)
            });
            entityManager.SetComponentData(instance, new Velocity {
                Value = random.NextFloat3Direction() * param.initSpeed
            });
            entityManager.SetComponentData(instance, new Acceleration {
                Value = float3.zero
            });

            // Dynamic Buffer の追加
            entityManager.AddBuffer <NeighborsEntityBuffer>(instance);
        }
    }
コード例 #7
0
        void Start()
        {
            var       em     = World.Active.EntityManager;
            var       random = new Random(12345);
            const int NUM    = 1023 * 2;
            var       coltbl = new Color[] {
                Color.HSVToRGB(0.0f, 1f, 1f),
                Color.HSVToRGB(0.1f, 1f, 1f),
                Color.HSVToRGB(0.2f, 1f, 1f),
                Color.HSVToRGB(0.3f, 1f, 1f),
                Color.HSVToRGB(0.4f, 1f, 1f),
                Color.HSVToRGB(0.5f, 1f, 1f),
                Color.HSVToRGB(0.6f, 1f, 1f),
                Color.HSVToRGB(0.7f, 1f, 1f),
                Color.HSVToRGB(0.8f, 1f, 1f),
                Color.HSVToRGB(0.9f, 1f, 1f),
            };

            for (var i = 0; i < NUM; ++i)
            {
                var entity = em.CreateEntity(typeof(Translation),
                                             typeof(Rotation),
                                             typeof(TestTrailRaycasterComponent));
#if UNITY_EDITOR
                em.SetName(entity, "trailRoot");
#endif
                em.SetComponentData(entity, new TestTrailRaycasterComponent {
                    Direction = random.NextFloat3Direction(),
                });
                var col = coltbl[(i / 1023) % coltbl.Length];
                TrailSystem.Instantiate(entity, float3.zero, 0.02f /* width */, col,
                                        float3.zero, 1f / 60f /* update_interval */);
            }
        }
コード例 #8
0
        public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
        {
            var wanderChunk       = batchInChunk.GetNativeArray(wanderTypeHandle);
            var boidChunk         = batchInChunk.GetNativeArray(boidTypeHandle);
            var translationsChunk = batchInChunk.GetNativeArray(translationTypeHandle);
            var rotationsChunk    = batchInChunk.GetNativeArray(rotationTypeHandle);

            for (int i = 0; i < batchInChunk.Count; i++)
            {
                Wander      w    = wanderChunk[i];
                Translation p    = translationsChunk[i];
                Rotation    r    = rotationsChunk[i];
                Vector3     disp = w.jitter * ran.NextFloat3Direction() * dT;
                w.target += disp;
                w.target.Normalize();
                w.target *= w.radius;

                Vector3 localTarget = (Vector3.forward * w.distance) + w.target;

                Quaternion q           = r.Value;
                Vector3    pos         = p.Value;
                Vector3    worldTarget = (q * localTarget) + pos;
                w.force        = (worldTarget - pos) * weight;
                wanderChunk[i] = w;
            }
        }
コード例 #9
0
        public void Execute(ref Boid b, ref Seperation s)
        {
            Vector3 force = Vector3.zero;
            int     neighbourStartIndex = maxNeighbours * b.boidId;
            int     mySpineId           = b.boidId * (spineLength + 1);
            Vector3 myPosition          = positions[mySpineId + spineOffset];

            for (int i = 0; i < b.taggedCount; i++)
            {
                int neighbourId = neighbours[neighbourStartIndex + i];
                if (neighbourId == b.boidId)
                {
                    continue;
                }
                int neighbourSpineId = (neighbourId * (spineLength + 1)) + spineOffset;
                //Vector3 toNeighbour = positions[b.boidId] - positions[neighbourId];
                Vector3 toNeighbour = myPosition - positions[neighbourSpineId];
                float   mag         = toNeighbour.magnitude;
                //force += (Vector3.Normalize(toNeighbour) / mag);


                if (mag > 0) // Need this check otherwise this behaviour can return NAN
                {
                    force += (Vector3.Normalize(toNeighbour) / mag);
                }
                else
                {
                    // same position, so generate a random force
                    Vector3 f = random.NextFloat3Direction();
                    force += f * b.maxForce;
                }
            }
            s.force = force * weight;
        }
コード例 #10
0
            public void Execute(Entity entity, int index, [ReadOnly] ref RandomInitialHeading randomInitialHeading, ref Heading heading)
            {
                heading = new Heading
                {
                    Value = Random.NextFloat3Direction()
                };

                Commands.RemoveComponent <RandomInitialHeading>(index, entity);
            }
コード例 #11
0
        public unsafe void ConvexConvexDistanceEdgeCaseTest()
        {
            Random rnd      = new Random(0x90456148);
            uint   dbgShape = 0;
            uint   dbgTest  = 0;

            int numShapes = 500;
            int numTests  = 50;

            if (dbgShape > 0)
            {
                numShapes = 1;
                numTests  = 1;
            }

            for (int iShape = 0; iShape < numShapes; iShape++)
            {
                if (dbgShape > 0)
                {
                    rnd.state = dbgShape;
                }
                uint shapeState = rnd.state;

                // Generate a random collider
                ConvexCollider *collider = (ConvexCollider *)TestUtils.GenerateRandomConvex(ref rnd).GetUnsafePtr();

                for (int iTest = 0; iTest < numTests; iTest++)
                {
                    if (dbgTest > 0)
                    {
                        rnd.state = dbgTest;
                    }
                    uint testState = rnd.state;

                    // Generate random transform
                    float      distance        = math.pow(10.0f, rnd.NextFloat(-15.0f, -1.0f));
                    float      angle           = math.pow(10.0f, rnd.NextFloat(-15.0f, 0.0f));
                    MTransform queryFromTarget = new MTransform(
                        (rnd.NextInt(10) > 0) ? quaternion.AxisAngle(rnd.NextFloat3Direction(), angle) : quaternion.identity,
                        (rnd.NextInt(10) > 0) ? rnd.NextFloat3Direction() * distance : float3.zero);
                    TestConvexConvexDistance(collider, collider, queryFromTarget, "ConvexConvexDistanceEdgeCaseTest failed " + iShape + ", " + iTest + " (" + shapeState + ", " + testState + ")");
                }
            }
        }
コード例 #12
0
 void Update()
 {
     for (var i = 0; i < 4; ++i)
     {
         var pos = random_.NextFloat3(-100, 100);
         var dir = random_.NextFloat3Direction();
         var rot = quaternion.LookRotation(dir, new float3(0, 1, 0));
         MissileSystem.Instantiate(MissileManager.Prefab, pos, rot);
     }
 }
コード例 #13
0
        void test_fire()
        {
            var pos = Vector3.zero;

            for (var i = 0; i < 10; ++i)
            {
                var vel = random_.NextFloat3Direction() * 32f;
                BeamSystem.Instantiate(World.DefaultGameObjectInjectionWorld.EntityManager, BeamManager.Prefab, pos, vel, Time.GetCurrent());
            }
        }
コード例 #14
0
        void test_fire()
        {
            var pos = Vector3.zero;

            for (var i = 0; i < 10; ++i)
            {
                var vel = random_.NextFloat3Direction() * 32f;
                BeamSystem.Instantiate(World.Active.EntityManager, BeamManager.Prefab, pos, vel);
            }
        }
コード例 #15
0
    void Update()
    {
        for (int i = 0; i < 20; ++i)
        {
            // PrefabをInstance化
            var entity = entityManager.Instantiate(prefab);

            // Velocityを設定
            entityManager.SetComponentData(entity, new Velocity(random.NextFloat3Direction()));
        }
    }
コード例 #16
0
        void LeoECS()
        {
            _world = new EcsWorld();
            JobMoveSystem.MinSpeed         = param.minSpeed;
            JobMoveSystem.MaxSpeed         = param.maxSpeed;
            JobMoveSystem.BoidScale        = boidScale;
            JobMoveSystem.WallScale        = param.wallScale * 0.5f;
            JobMoveSystem.WallDistance     = param.wallDistance;
            JobMoveSystem.WallWeight       = param.wallWeight;
            JobMoveSystem.NeighborFov      = math.cos(math.radians(param.neighborFov));
            JobMoveSystem.NeighborDistance = param.neighborDistance;
            JobMoveSystem.SeparationWeight = param.separationWeight;
            JobMoveSystem.AlignmentWeight  = param.alignmentWeight;
            JobMoveSystem.CohesionWeight   = param.cohesionWeight;
            JobMoveSystem.EntitiesCount    = boidCount;
            JobMoveSystem.NumBoidsPerJob   = boidCount / System.Environment.ProcessorCount;

            if (BoidsVisualisationSystem._nativeMatrices.IsCreated)
            {
                BoidsVisualisationSystem._nativeMatrices.Dispose();
            }
            BoidsVisualisationSystem._nativeMatrices = new NativeArray <Matrix4x4> (boidCount, Allocator.Persistent);
            BoidsVisualisationSystem._matrices       = new Matrix4x4[boidCount];

            var timeSystem = new TimeSystem();

            _systems = new EcsSystems(_world);
            _systems
            .Add(timeSystem)
            .Add(new BoidsSimulationSystem())
            .Add(new JobMoveSystem())
            .Add(new BoidsVisualisationSystem()
            {
                mesh = mesh, material = material, scale = boidScale
            })
            .Inject(timeSystem)
            .Initialize();
            var random = new Unity.Mathematics.Random(853);

            BoidEntityData.Create(boidCount);

            for (int i = 0; i < boidCount; ++i)
            {
                var initSpeed = param.initSpeed;
                //init them with these default values
                var boid = _world.CreateEntityWith <BoidEntityData> ();
                boid.id           = i;
                boid.Position     = random.NextFloat3(1f);
                boid.Velocity     = random.NextFloat3Direction() * initSpeed;;
                boid.Acceleration = float3.zero;
            }
            _world.ProcessDelayedUpdates();
        }
コード例 #17
0
 void test_distortion()
 {
     for (var i = 0; i < 1; ++i)
     {
         var pos = random_.NextFloat3Direction() * 4f;
         DistortionSystem.Instantiate(World.Active.EntityManager,
                                      DistortionManager.Prefab,
                                      pos,
                                      10f /* period */,
                                      1f /* size */);
     }
 }
コード例 #18
0
 void test_distortion()
 {
     for (var i = 0; i < 1; ++i)
     {
         var pos = random_.NextFloat3Direction() * 4f;
         DistortionSystem.Instantiate(World.DefaultGameObjectInjectionWorld.EntityManager,
                                      DistortionManager.Prefab,
                                      pos,
                                      10f /* period */,
                                      1f /* size */,
                                      Time.GetCurrent());
     }
 }
コード例 #19
0
    protected override void OnUpdate()
    {
        if (!init)
        {
            var random          = new Unity.Mathematics.Random(853);
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = whalesGhostSerializerCollection.FindGhostType <BoidSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;

            for (int i = 0; i < Bootstrap.Instance.boidCount; ++i)
            {
                var boid = EntityManager.Instantiate(prefab);

                EntityManager.SetComponentData(boid, new Translation {
                    Value = random.NextFloat3(1f)
                });
                EntityManager.SetComponentData(boid, new Rotation {
                    Value = quaternion.identity
                });
                EntityManager.SetComponentData(boid, new Velocity {
                    Value = random.NextFloat3Direction() * Bootstrap.Param.initSpeed
                });
                EntityManager.SetComponentData(boid, new Acceleration {
                    Value = float3.zero
                });
                EntityManager.AddBuffer <NeighborsEntityBuffer>(boid);
            }
            init = true;
        }

        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(string.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();

            var playerGhostId = whalesGhostSerializerCollection.FindGhostType <WhaleSnapshotData>();
            var playerPrefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[playerGhostId].Value;
            var player        = EntityManager.Instantiate(playerPrefab);
            EntityManager.SetComponentData(player, new PlayerComponent {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });
            PostUpdateCommands.AddBuffer <InputCommandData>(player);

            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });
            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
コード例 #20
0
 public Entity SetupEntity(Entity entity, Entity parent, MeshInstanceRenderer renderer, float scale)
 {
     EntityManager.SetComponentData(entity, new Position {
         Value = _rand.NextFloat3Direction() * scale * 10
     });
     EntityManager.SetComponentData(entity, new Scale {
         Value = scale
     });
     EntityManager.SetSharedComponentData(entity, renderer);
     EntityManager.AddComponentData(EntityManager.CreateEntity(), new Attach {
         Parent = parent, Child = entity
     });
     return(entity);
 }
コード例 #21
0
    // Start is called before the first frame update
    private void Start()
    {
        _positions = new NativeArray <float3>(NumObjects, Allocator.Persistent);

        _filteredIndices = new NativeList <int>(NumObjects, Allocator.Persistent);

        Unity.Mathematics.Random rand = new Unity.Mathematics.Random(123);

        for (int i = 0; i < NumObjects; i++)
        {
            _positions[i] = rand.NextFloat3Direction() * rand.NextFloat(1f, 50f);
        }

        _renderer = new IndirectRenderer(NumObjects, Material, Mesh);
    }
コード例 #22
0
    private void EmitAlongJoint(UnitySkeleton skeleton, JointId a, JointId b)
    {
        var jointA = skeleton.GetJoint(a);
        var jointB = skeleton.GetJoint(b);

        var pos = math.lerp(jointA.position, jointB.position, _rng.NextFloat());

        pos    = _mirror.InverseTransformPoint(pos);
        pos.z *= -1f;
        pos    = _mirror.TransformPoint(pos);

        var vel = _rng.NextFloat3Direction() * 0.0001f;

        _particles.Emit(pos, vel, 0.1f, 4f, Color.green);
    }
コード例 #23
0
        private static void GetRandomDirections(vec3 halfVoxel, uint seed, ref NativeArray <vec3> samples)
        {
            int count = samples.Length;

#if USE_BURST_AND_MATH
            Random random = new Random(seed);
#endif
            for (int k = 0; k < count; k++)
            {
#if USE_BURST_AND_MATH
                samples[k] = random.NextFloat3Direction() * halfVoxel;
#else
                samples[k] = Vector3.Scale(Random.onUnitSphere, halfVoxel);
#endif
            }
        }
コード例 #24
0
        public void Execute(ref Boid b, ref Wander w, ref Position p, ref Rotation r)
        {
            Vector3 disp = w.jitter * random.NextFloat3Direction() * dT;

            w.target += disp;
            w.target.Normalize();
            w.target *= w.radius;

            Vector3 localTarget = (Vector3.forward * w.distance) + w.target;

            Quaternion q           = r.Value;
            Vector3    pos         = p.Value;
            Vector3    worldTarget = (q * localTarget) + pos;

            w.force = (worldTarget - pos) * weight;
        }
コード例 #25
0
        public void Execute(Entity entity, int index, ref LocalToWorld localToWorld, ref Velocity velocity)
        {
            float3 normal;

            jobDistancesFromIsoSurface[index] = DistanceFieldMathUtil.GetDistance(localToWorld.Position.x, localToWorld.Position.y, localToWorld.Position.z, deltaTime, jobDistanceFieldModel, out normal);

            velocity.Value -= math.normalize(normal) * jobSettings.attraction * math.clamp(jobDistancesFromIsoSurface[index], -1f, 1f);
            velocity.Value += jobRNG.NextFloat3Direction() * jobSettings.jitter;
            velocity.Value *= .99f;

            localToWorld = new LocalToWorld
            {
                Value = float4x4.TRS(
                    new float3(localToWorld.Position + velocity.Value),
                    quaternion.LookRotationSafe(velocity.Value, math.up()),
                    new float3(.1f, .01f, math.max(.1f, math.length(velocity.Value) * jobSettings.speedStretch)))
            };
        }
コード例 #26
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        // Unity.Mathematics.Random
        // Seed cannot be 0 (zero).
        var random     = new Random((uint)Environment.TickCount);
        var entityList = new NativeList <Entity>(Allocator.TempJob);

        Entities
        .WithStoreEntityQueryInField(ref m_Query)
        .ForEach((Instantiator instantiator) => {
            // This will set the Length and resize the internal array if needed
            entityList.ResizeUninitialized(instantiator.Count);

            EntityManager.Instantiate(instantiator.Prefab, entityList);

            for (var entityIndex = 0; entityIndex < entityList.Length; entityIndex++)
            {
                var entity   = entityList[entityIndex];
                var position = new float3()
                {
                    x = UnityEngine.Random.Range(-2.5f, 2.5f), y = UnityEngine.Random.Range(2f, 20f), z = UnityEngine.Random.Range(-2.5f, 2.5f)
                };
                EntityManager.SetComponentData(entity, new Translation
                {
                    Value = random.NextFloat3Direction() * random.NextFloat(-2, 2)
                });

                EntityManager.SetComponentData(entity, new Rotation
                {
                    Value = random.NextQuaternionRotation()
                });
            }
        })
        .WithStructuralChanges()
        .WithoutBurst()
        .Run();

        entityList.Dispose();

        // That's a batch operation for all entities captures in the query and scale really well.
        EntityManager.DestroyEntity(m_Query);

        return(inputDeps);
    }
コード例 #27
0
        public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
        {
            var boidChunk         = batchInChunk.GetNativeArray(boidTypeHandle);
            var translationsChunk = batchInChunk.GetNativeArray(translationTypeHandle);
            var seperationChunk   = batchInChunk.GetNativeArray(seperationTypeHandle);

            for (int i = 0; i < batchInChunk.Count; i++)
            {
                Vector3     force = Vector3.zero;
                Translation p     = translationsChunk[i];
                Seperation  s     = seperationChunk[i];
                Boid        b     = boidChunk[i];

                for (int j = 0; j < b.taggedCount; j++)
                {
                    int neighbourStartIndex = maxNeighbours * b.boidId;

                    Vector3 myPosition = positions[b.boidId];


                    int neighbourId = neighbours[neighbourStartIndex + j];
                    if (neighbourId == b.boidId)
                    {
                        continue;
                    }
                    Vector3 toNeighbour = positions[b.boidId] - positions[neighbourId];
                    float   mag         = toNeighbour.magnitude;

                    if (mag > 0) // Need this check otherwise this behaviour can return NAN
                    {
                        force += (Vector3.Normalize(toNeighbour) / mag);
                    }
                    else
                    {
                        // same position, so generate a random force
                        Vector3 f = random.NextFloat3Direction();
                        force += f * b.maxForce;
                    }
                }
                s.force            = force * weight;
                seperationChunk[i] = s;
            }
        }
コード例 #28
0
    public unsafe int GetPoints(int i, float3 *dest)
    {
        Unity.Mathematics.Random rng = new Unity.Mathematics.Random(m_Seeds[i]);
        int numPoints = GetNumPoints(ref rng);
        int count     = 0;

        while (count < numPoints)
        {
            float3 n = rng.NextFloat3Direction();
            float3 c = n * rng.NextFloat(0.0f, 1.0f);
            Math.CalculatePerpendicularNormalized(n, out float3 u, out float3 v);
            int planePoints = math.min(rng.NextInt(3, 20), numPoints - count);
            for (int iPoint = 0; iPoint < planePoints; iPoint++)
            {
                dest[count++] = c + u * rng.NextFloat(-1.0f, 1.0f) + v * rng.NextFloat(-1.0f, 1.0f);
            }
        }
        return(numPoints);
    }
コード例 #29
0
        void SveltoECS()
        {
            //creates the _enginesRoot, for more information read my svelto.ECS articles
            _enginesRoot = new EnginesRoot(new UnityEntitySubmissionScheduler());
            //this will be used to build entities
            var entityFactory = _enginesRoot.GenerateEntityFactory();
            var random        = new Unity.Mathematics.Random(853);

            for (int i = 0; i < boidCount; ++i)
            {
                var initSpeed = param.initSpeed;

                //build entities in the BOIDS_GROUP exclusive group
                var entityStructInitializer = entityFactory.BuildEntity <BoidEntityDecriptor>(i, GAME_GROUPS.BOIDS_GROUP);
                var nextFloat3 = random.NextFloat3(1f);
                var float3     = random.NextFloat3Direction() * initSpeed;
                //init them with these default values
                entityStructInitializer.Init(new BoidEntityStruct()
                {
                    position = new SVector3 {
                        x = nextFloat3.x, y = nextFloat3.y, z = nextFloat3.z
                    },
                    rotation = new SVector4 {
                        x = 0, y = 0, z = 0, w = 1
                    },
                    velocity = new SVector3 {
                        x = float3.x, y = float3.y, z = float3.z
                    },
                    acceleration = new SVector3()
                });
            }

            //create a synchronization enumerator to be used inside the Svelto.Tasks
            ThreadSynchronizationSignal _signal = new ThreadSynchronizationSignal("name");

            //add the engines we are going to use
            _enginesRoot.AddEngine(new BoidsSyncronizationEngine(_unityECSGroup, _signal));
            _enginesRoot.AddEngine(new BoidsSimulationEngine(_signal, param, boidCount));
        }
コード例 #30
0
        void CreateEntity()
        {
            var scale     = Bootstrap.Boid.scale;
            var initSpeed = Bootstrap.Param.initSpeed;

            PostUpdateCommands.CreateEntity(archetype);
            PostUpdateCommands.SetComponent(new Position {
                Value = random.NextFloat3(1f)
            });
            PostUpdateCommands.SetComponent(new Rotation {
                Value = quaternion.identity
            });
            PostUpdateCommands.SetComponent(new Scale {
                Value = new float3(scale.x, scale.y, scale.z)
            });
            PostUpdateCommands.SetComponent(new Velocity {
                Value = random.NextFloat3Direction() * initSpeed
            });
            PostUpdateCommands.SetComponent(new Acceleration {
                Value = float3.zero
            });
            PostUpdateCommands.SetSharedComponent(renderer);
        }