Beispiel #1
0
    protected override void OnUpdate()
    {
        var dampWeight = Time.DeltaTime / 0.5f;
        var time       = Time.ElapsedTime;

        Dependency = Entities
                     .ForEach((Entity entity, ref LocalToWorld localToWorld, ref AnimationControllerData data, ref AnimationControllerDataInput input) =>
        {
            var rootX = new RigidTransform(localToWorld.Value);

            if (data.Player == 0)
            {
                var rand = new Unity.Mathematics.Random((uint)entity.Index + (uint)math.fmod(time * 1000, 1000));

                data.Direction += rand.NextBool() ? -0.1f : 0.1f;
                data.Direction  = math.clamp(data.Direction, 0, 4);

                data.Speed += rand.NextBool() ? -0.1f : 0.1f;
                data.Speed  = math.clamp(data.Speed, 0, 1);
            }

            data.Player = 0;

            data.DirectionDamped    = math.lerp(data.DirectionDamped, data.Direction, dampWeight);
            input.MixerWalkJobBlend = data.DirectionDamped;

            data.SpeedDamped       = math.lerp(data.SpeedDamped, data.Speed, dampWeight);
            input.TimeCounterSpeed = 1.0f + 0.5f * data.SpeedDamped;
            input.MixerSpeedBlend  = data.SpeedDamped;

            data.FollowX.pos = math.lerp(data.FollowX.pos, rootX.pos, dampWeight);
            data.FollowX.rot = mathex.lerp(math.normalizesafe(data.FollowX.rot), rootX.rot, dampWeight);
        }).ScheduleParallel(Dependency);
    }
Beispiel #2
0
        void generateRandomMotion(ref Random rnd, out MotionVelocity velocity, out MotionData motion, bool allowInfiniteMass)
        {
            motion = new MotionData
            {
                WorldFromMotion = generateRandomTransform(ref rnd),
                BodyFromMotion  = generateRandomTransform(ref rnd)
            };

            float3 inertia = rnd.NextFloat3(1e-3f, 100.0f);

            switch (rnd.NextInt(3))
            {
            case 0:     // all values random
                break;

            case 1:     // two values the same
                int index = rnd.NextInt(3);
                inertia[(index + 1) % 2] = inertia[index];
                break;

            case 2:     // all values the same
                inertia = inertia.zzz;
                break;
            }

            velocity = new MotionVelocity
            {
                LinearVelocity        = rnd.NextBool() ? float3.zero : rnd.NextFloat3(-50.0f, 50.0f),
                AngularVelocity       = rnd.NextBool() ? float3.zero : rnd.NextFloat3(-50.0f, 50.0f),
                InverseInertiaAndMass = (allowInfiniteMass && rnd.NextBool()) ? float4.zero : new float4(1.0f / inertia, rnd.NextFloat(1e-3f, 100.0f))
            };
        }
    protected override void UpdateGraph(Entity entity, NodeSet set, ref AnimationControllerData data)
    {
        RigidTransform rootX = RigidTransform.identity;

        rootX.pos = EntityManager.GetComponentData <Translation>(entity).Value;
        rootX.rot = EntityManager.GetComponentData <Rotation>(entity).Value;

        var dampWeight = Time.DeltaTime / 0.5f;

        if (data.Player == 0)
        {
            var rand = new Unity.Mathematics.Random((uint)entity.Index + (uint)math.fmod((float)Time.ElapsedTime * 1000, 1000));

            data.Direction += rand.NextBool() ? -0.1f : 0.1f;
            data.Direction  = math.clamp(data.Direction, 0, 4);

            data.Speed += rand.NextBool() ? -0.1f : 0.1f;
            data.Speed  = math.clamp(data.Speed, 0, 1);
        }

        data.Player = 0;

        data.DirectionDamped = math.lerp(data.DirectionDamped, data.Direction, dampWeight);
        set.SendMessage(data.MixerWalkNode, (InputPortID)DirectionMixerNode.SimulationPorts.Blend, data.DirectionDamped);
        set.SendMessage(data.MixerJogNode, (InputPortID)DirectionMixerNode.SimulationPorts.Blend, data.DirectionDamped);

        data.SpeedDamped = math.lerp(data.SpeedDamped, data.Speed, dampWeight);
        set.SendMessage(data.TimeCounterNode, (InputPortID)TimeCounterNode.SimulationPorts.Speed, 1.0f + 0.5f * data.SpeedDamped);
        set.SendMessage(data.MixerSpeedNode, (InputPortID)MixerNode.SimulationPorts.Blend, data.SpeedDamped);
        set.SetData(data.RootMotionNode, (InputPortID)RootMotionNode.KernelPorts.PrevRootX, rootX);

        data.FollowX.pos = math.lerp(data.FollowX.pos, rootX.pos, dampWeight);
        data.FollowX.rot = math.nlerp(math.normalizesafe(data.FollowX.rot), rootX.rot, dampWeight);
    }
Beispiel #4
0
    public unsafe int GetPoints(int i, float3 *dest)
    {
        Unity.Mathematics.Random rng = new Unity.Mathematics.Random(m_Seeds[i]);
        GetResolution(ref rng, out int res0, out int res1);
        float scale  = rng.NextBool() ? 1.0f : rng.NextFloat(1.0f, 5.0f);
        float radius = rng.NextFloat(0.01f, 1.0f / scale);

        // Generate points
        int numPoints;

        if (res1 == 0)
        {
            // Random scattered points
            for (int iPoint = 0; iPoint < res0; iPoint++)
            {
                dest[iPoint] = math.normalize(rng.NextFloat3(-1, 1)) * radius;
            }
            numPoints = res0;
        }
        else
        {
            // Spherical coordinates
            int iPoint = 0;
            for (int iPhi = 0; iPhi < res0; iPhi++)
            {
                float phi    = (2 * iPhi + 1) * math.PI / res0;
                float sinPhi = math.sin(phi);
                float cosPhi = math.cos(phi);
                for (int iTheta = 0; iTheta < res1; iTheta++)
                {
                    float theta    = 0.5f * (2 * iTheta + 1) * math.PI / res1;
                    float sinTheta = math.sin(theta);
                    float cosTheta = math.cos(theta);
                    dest[iPoint++] = new float3(radius * sinTheta * cosPhi, radius * sinTheta * sinPhi, radius * cosTheta);
                }
            }
            numPoints = iPoint;
        }

        // Offset, scale and rotate
        float3     center      = rng.NextBool() ? float3.zero : rng.NextFloat3(1.0f);
        quaternion orientation = rng.NextBool() ? quaternion.identity : rng.NextQuaternionRotation();

        for (int iPoint = 0; iPoint < numPoints; iPoint++)
        {
            dest[iPoint] = math.mul(orientation, dest[iPoint] * new float3(scale, 1, 1) + center);
        }

        return(numPoints);
    }
        ControllerUnit fetch_random(double time)
        {
            var unit = new ControllerUnit {
                Horizontal  = _random.NextFloat(),
                Vertical    = _random.NextFloat(),
                FireBullet  = _random.NextBool(),
                FireMissile = _random.NextBool(),
                Toward      = _random.NextBool(),
                Away        = _random.NextBool(),
                Condition   = _random.NextFloat(),
                Time        = (float)(time - _startTime),
            };

            return(unit);
        }
        public unsafe void TestMeshColliderCreateWithInvalidIndices()
        {
            int numTriangles = 10;
            var vertices     = new NativeArray <float3>(numTriangles * 3, Allocator.Persistent);
            var triangles    = new NativeArray <int>(numTriangles * 3, Allocator.Persistent);

            for (int i = 0; i < numTriangles * 3; i++)
            {
                vertices[i]  = new float3((float)i, 1.0f * (float)(i % 2), (float)(i + 1));
                triangles[i] = i;
            }

            Random rnd = new Random(0x12345678);

            for (int i = 0; i < 100; i++)
            {
                int indexToChange = rnd.NextInt(0, triangles.Length - 1);

                int invalidValue = rnd.NextInt() * (rnd.NextBool() ? -1 : 1);
                triangles[indexToChange] = invalidValue;

                TestUtils.ThrowsException <System.ArgumentException>(
                    () => Unity.Physics.MeshCollider.Create(vertices, triangles)
                    );

                triangles[indexToChange] = indexToChange;
            }


            triangles.Dispose();
            vertices.Dispose();
        }
Beispiel #7
0
        //
        // Random test data generation
        //

        static float3 generateRandomCardinalAxis(ref Random rnd)
        {
            float3 axis = float3.zero;

            axis[rnd.NextInt(3)] = rnd.NextBool() ? 1 : -1;
            return(axis);
        }
Beispiel #8
0
        public void PathRandomObstacles()
        {
            using (var grid = new TestGrid(31))
            {
                int obstacleCount = 32;
                var rand          = new Unity.Mathematics.Random(0xF545AA3F);
                for (int i = 0; i < obstacleCount; i++)
                {
                    var faceIndex      = rand.NextInt(0, 6);
                    var xy             = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)xy.x, y = (short)xy.y
                    };
                    var cubeFace = new CartesianGridOnCubeFace {
                        Value = (byte)faceIndex
                    };
                    var cellIndex = CartesianGridOnCubeUtility.CellIndex(sourcePosition, cubeFace, grid.RowCount);
                    if (rand.NextBool())
                    {
                        grid.AddWallWest(cellIndex);
                    }
                    else
                    {
                        grid.AddWallSouth(cellIndex);
                    }
                }

                int testCount = 64;
                for (int i = 0; i < testCount; i++)
                {
                    var sourceXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourceFaceIndex = rand.NextInt(0, 6);
                    var sourceCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)sourceFaceIndex
                    };
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)sourceXY.x, y = (short)sourceXY.y
                    };

                    var targetXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var targetFaceIndex = rand.NextInt(0, 6);
                    var targetCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)targetFaceIndex
                    };
                    var targetPosition = new CartesianGridCoordinates {
                        x = (short)targetXY.x, y = (short)targetXY.y
                    };

                    grid.WalkPathDistance(sourcePosition, sourceCubeFace, targetPosition, targetCubeFace);
                }
            }
        }
Beispiel #9
0
    private void GetResolution(ref Unity.Mathematics.Random rng, out int res0, out int res1)
    {
        bool random = rng.NextBool();

        if (random)
        {
            res0 = rng.NextInt(1, 500);
            res1 = 0;
        }
        else
        {
            res0 = rng.NextInt(1, 20);
            res1 = rng.NextInt(1, 20);
        }
    }
        unsafe ComponentType[] CreateRandomMatchingQueryTypes(NativeArray <EntityArchetype> archetypes)
        {
            var random  = new Random(34343);
            var typeSet = new HashSet <ComponentType>();

            for (int i = 0; i < archetypes.Length; i++)
            {
                if (random.NextBool())
                {
                    for (int typeIndex = 0; typeIndex < archetypes[i].Archetype->TypesCount; typeIndex++)
                    {
                        typeSet.Add(archetypes[i].Archetype->Types[0].ToComponentType());
                    }
                }
            }

            return(typeSet.ToArray());
        }
Beispiel #11
0
        public void MeshCollider_Create_WhenTriangleIndexOutOfRange_Throws()
        {
            int numTriangles = 10;
            var vertices     = new NativeArray <float3>(numTriangles * 3, Allocator.Persistent);
            var triangles    = new NativeArray <int3>(numTriangles, Allocator.Persistent);

            try
            {
                for (int i = 0; i < numTriangles; i++)
                {
                    int firstVertexIndex = i * 3;

                    vertices[firstVertexIndex]     = new float3(firstVertexIndex, 1f * (firstVertexIndex % 2), firstVertexIndex + 1);
                    vertices[firstVertexIndex + 1] = new float3(firstVertexIndex + 1, 1f * ((firstVertexIndex + 1) % 2), firstVertexIndex + 2);
                    vertices[firstVertexIndex + 2] = new float3(firstVertexIndex + 2, 1f * ((firstVertexIndex + 2) % 2), firstVertexIndex + 3);
                    triangles[i] = new int3(firstVertexIndex, firstVertexIndex + 1, firstVertexIndex + 2);
                }

                Random rnd = new Random(0x12345678);

                for (int i = 0; i < 100; i++)
                {
                    int indexToChange = rnd.NextInt(0, triangles.Length * 3 - 1);

                    int triangleIndex    = indexToChange / 3;
                    int vertexInTriangle = indexToChange % 3;
                    int invalidValue     = rnd.NextInt() * (rnd.NextBool() ? -1 : 1);

                    var triangle = triangles[triangleIndex];
                    triangle[vertexInTriangle] = invalidValue;
                    triangles[triangleIndex]   = triangle;

                    Assert.Throws <ArgumentException>(() => MeshCollider.Create(vertices, triangles));

                    triangle[vertexInTriangle] = indexToChange;
                    triangles[triangleIndex]   = triangle;
                }
            }
            finally
            {
                triangles.Dispose();
                vertices.Dispose();
            }
        }
Beispiel #12
0
    public bool Update(ValueWithNeighbors <Chunk> chunkWithNeighbors, int2 cellPosition, Random random)
    {
        Cell?GetCellAtOffset(int2 offset)
        {
            return(CellUtils.GetCellAtPosition(chunkWithNeighbors, cellPosition + offset));
        }

        bool MoveTo(int2 offset)
        {
            return(CellUtils.SwitchCells(chunkWithNeighbors, cellPosition, offset));
        }

        var randomDirection = random.NextBool() ? -1 : 1;

        {
            var cellType = GetCellAtOffset(int2(0, -1))?.type;

            if (cellType == CellType.None || cellType == CellType.Water)
            {
                return(MoveTo(int2(0, -1)));
            }
        }

        {
            var cellType = GetCellAtOffset(int2(randomDirection, -1))?.type;

            if (cellType == CellType.None || cellType == CellType.Water)
            {
                return(MoveTo(int2(randomDirection, -1)));
            }
        }

        {
            var cellType = GetCellAtOffset(int2(-randomDirection, -1))?.type;

            if (cellType == CellType.None || cellType == CellType.Water)
            {
                return(MoveTo(int2(-randomDirection, -1)));
            }
        }

        return(false);
    }
Beispiel #13
0
        public void Execute(TriggerEvent triggerEvent)
        {
            var txAutotrophConsts = environmentSettings[0].txAutotrophConsts;
            var eA = triggerEvent.Entities.EntityA;
            var eB = triggerEvent.Entities.EntityB;


            Entity e;
            Entity eOther;


            if (TxAutotrophPollen.Exists(eA) || TxAutotrophPollen.Exists(eB))
            {
                if (TxAutotrophPollen.Exists(eA))
                {
                    eOther = eA;
                    e      = eB;
                }
                else
                {
                    e      = eA;
                    eOther = eB;
                }
                float distance = txAutotrophChrome2AB[TxAutotrophPollen[eOther].plant].DistanceSq(
                    txAutotrophChrome2AB[e], txAutotrophConsts.crossBreedDistance
                    );
                if (random.NextFloat(0, 1) > distance)
                {
                    if (!fertilizeDict.ContainsKey(e))
                    {
                        fertilizeDict[e] = eOther;
                    }
                    else
                    {
                        if (random.NextBool())
                        {
                            fertilizeDict[e] = eOther;
                        }
                    }
                }
            }
        }
Beispiel #14
0
        public unsafe void TestMeshColliderCreateWithInvalidIndices()
        {
            int numTriangles = 10;
            var vertices     = new NativeArray <float3>(numTriangles * 3, Allocator.Persistent);
            var triangles    = new NativeArray <int3>(numTriangles, Allocator.Persistent);

            for (int i = 0; i < numTriangles; i++)
            {
                int firstVertexIndex = i * 3;

                vertices[firstVertexIndex]     = new float3((float)firstVertexIndex, 1.0f * (float)(firstVertexIndex % 2), (float)(firstVertexIndex + 1));
                vertices[firstVertexIndex + 1] = new float3((float)(firstVertexIndex + 1), 1.0f * (float)((firstVertexIndex + 1) % 2), (float)(firstVertexIndex + 2));
                vertices[firstVertexIndex + 2] = new float3((float)(firstVertexIndex + 2), 1.0f * (float)((firstVertexIndex + 2) % 2), (float)(firstVertexIndex + 3));
                triangles[i] = new int3(firstVertexIndex, firstVertexIndex + 1, firstVertexIndex + 2);
            }

            Random rnd = new Random(0x12345678);

            for (int i = 0; i < 100; i++)
            {
                int indexToChange = rnd.NextInt(0, triangles.Length * 3 - 1);

                int triangleIndex    = indexToChange / 3;
                int vertexInTriangle = indexToChange % 3;
                int invalidValue     = rnd.NextInt() * (rnd.NextBool() ? -1 : 1);

                var triangle = triangles[triangleIndex];
                triangle[vertexInTriangle] = invalidValue;
                triangles[triangleIndex]   = triangle;

                TestUtils.ThrowsException <System.ArgumentException>(
                    () => Unity.Physics.MeshCollider.Create(vertices, triangles)
                    );

                triangle[vertexInTriangle] = indexToChange;
                triangles[triangleIndex]   = triangle;
            }

            triangles.Dispose();
            vertices.Dispose();
        }
        public void PathRandomObstacles()
        {
            using (var grid = new TestGrid(32, 15))
            {
                int obstacleCount = 32;
                var rand          = new Unity.Mathematics.Random(0xF545AA3F);
                for (int i = 0; i < obstacleCount; i++)
                {
                    var xy = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    if (rand.NextBool())
                    {
                        grid.AddWallWest(new CartesianGridCoordinates {
                            x = (short)xy.x, y = (short)xy.y
                        });
                    }
                    else
                    {
                        grid.AddWallSouth(new CartesianGridCoordinates {
                            x = (short)xy.x, y = (short)xy.y
                        });
                    }
                }

                int testCount = 64;
                for (int i = 0; i < testCount; i++)
                {
                    var sourceXY       = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    var targetXY       = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)sourceXY.x, y = (short)sourceXY.y
                    };
                    var targetPosition = new CartesianGridCoordinates {
                        x = (short)targetXY.x, y = (short)targetXY.y
                    };
                    grid.WalkPathDistance(sourcePosition, targetPosition);
                }
            }
        }
Beispiel #16
0
        static RigidTransform generateRandomTransform(ref Random rnd)
        {
            // Random rotation: 1 in 4 are identity, 3 in 16 are 90 or 180 degrees about i j or k, the rest are uniform random
            quaternion rot = quaternion.identity;

            if (rnd.NextInt(4) > 0)
            {
                if (rnd.NextInt(4) > 0)
                {
                    rot = rnd.NextQuaternionRotation();
                }
                else
                {
                    float angle = rnd.NextBool() ? 90 : 180;
                    rot = quaternion.AxisAngle(generateRandomCardinalAxis(ref rnd), angle);
                }
            }

            return(new RigidTransform()
            {
                pos = rnd.NextInt(4) == 0 ? float3.zero : rnd.NextFloat3(-1.0f, 1.0f),
                rot = rot
            });
        }
Beispiel #17
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var commandBuffer    = _barrier.CreateCommandBuffer();
            var conCommandBuffer = commandBuffer.ToConcurrent();

            var mapEntity = _mapQuery.GetSingletonEntity();
            var genData   = EntityManager.GetComponentData <GenerateMap>(mapEntity);
            var mapData   = EntityManager.GetComponentData <MapData>(mapEntity);
            var map       = EntityManager.GetBuffer <MapTiles>(mapEntity);
            var rooms     = EntityManager.GetBuffer <MapRooms>(mapEntity).Reinterpret <IntRect>();

            // If the seed is '0' we want to pass in a random seed.
            int randomSeed = UnityEngine.Random.Range(1, int.MaxValue);

            genData.seed = genData.seed == 0 ? randomSeed : genData.seed;
            uint seed = (uint)genData.seed;

            Debug.Log("GENERATING MAP");

            inputDeps = Job
                        .WithCode(() =>
            {
                int w = mapData.width;
                int h = mapData.height;

                InitializeMap(map, w, h);

                rooms.Clear();

                GenerateRooms(map, mapData, genData, rooms);
            }).Schedule(inputDeps);

            inputDeps = Entities
                        .WithReadOnly(rooms)
                        .WithAll <Player>()
                        .ForEach((int entityInQueryIndex, Entity e, ref Position p) =>
            {
                p.value = rooms[0].Center;
            }).Schedule(inputDeps);

            // Destroy existing monsters
            inputDeps = Entities
                        .WithNone <Player>()
                        .WithAll <Renderable>()
                        .WithAll <Position>()
                        .ForEach((int entityInQueryIndex, Entity e) =>
            {
                conCommandBuffer.DestroyEntity(entityInQueryIndex, e);
            }).Schedule(inputDeps);


            FixedString32 goblinName = new FixedString32("Goblin");
            FixedString32 orcName    = new FixedString32("Orc");

            var arch = _monsterArchetype;

            // Make monsters
            inputDeps = Job.WithCode(() =>
            {
                Random rand = new Random(seed);

                for (int i = 1; i < rooms.Length; ++i)
                {
                    var room    = rooms[i];
                    var monster = commandBuffer.CreateEntity(arch);

                    bool flip = rand.NextBool();

                    FixedString32 name = default;
                    char c             = default;

                    if (flip)
                    {
                        c    = 'g';
                        name = goblinName;
                    }
                    else
                    {
                        c    = 'o';
                        name = orcName;
                    }
                    commandBuffer.SetComponent(
                        monster,
                        new Renderable(c, Color.red)
                        );
                    commandBuffer.SetComponent <Position>(monster, room.Center);
                    commandBuffer.SetComponent <ViewRange>(monster, 5);
                    commandBuffer.SetComponent <Name>(monster, name);
                }
            }).Schedule(inputDeps);

            commandBuffer.RemoveComponent <GenerateMap>(_mapQuery);
            _barrier.AddJobHandleForProducer(inputDeps);

            return(inputDeps);
        }
Beispiel #18
0
    public int FindBestAction(ref NativeList <NodeAStar> listeNodes, ref WindjermanGameState gs, ref NativeList <int> availableActions)
    {
        float newDistancefromFrisbee = currentDistanceFromFrisbee;
        int   indexClosestToFrisbee  = 0;

        //si le joueur n'a pas le frisbee a l'instant T les bonnes action sont celles qui rapprochent le joueur de celui-ci
        if (playerID == 0)
        {
            if (!gs.isFreeze1 && gs.frisbeePosition.x < 0)
            {
                for (int i = 0; i < listeNodes.Length; i++)
                {
                    //si l'action permet d'attraper le frisbee on la sélectionne
                    if (listeNodes[i].hasFrisbee)
                    {
                        //listeNodes.Dispose();
                        return(i);
                    }
                    else
                    {
                        //si l'action réduit la distance entre le joueur et le frisbee, on conserve le résultat de cette action
                        if (listeNodes[i].getDistanceFromFrisbee() < currentDistanceFromFrisbee)
                        {
                            indexClosestToFrisbee      = i;
                            currentDistanceFromFrisbee = listeNodes[i].getDistanceFromFrisbee();
                        }
                    }
                }

                //listeNodes.Dispose();
                return(indexClosestToFrisbee);
            }
            else
            {
                //si le joueur a le frisbee, les bonnes actions sont celles qui lancent le frisbee loin de l'autre joueur
                for (int i = 0; i < listeNodes.Length; i++)
                {
                    //si le joueur a le highground, tirer tout droit est la meilleure option
                    if (highGround)
                    {
                        //tirer tout droit est la meilleure option mais on ajoute une variation pour rendre le bot moins prédictible
                        Unity.Mathematics.Random random = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, 100000));
                        float proba = random.NextFloat(0f, 3f);

                        //si proba inférieure à 1, l'agent tire en diagonale
                        if (proba < 1f)
                        {
                            bool probaDirection = random.NextBool();

                            if (probaDirection)
                            {
                                //tir en bas
                                if (listeNodes[i].gsNode.frisbeePosition.y < listeNodes[i].gsNode.playerPosition1.y)
                                {
                                    lastActionDone = availableActions[i];
                                    listeNodes.Dispose();
                                    return(i);
                                }
                            }
                            else
                            {
                                //tir en haut
                                if (listeNodes[i].gsNode.frisbeePosition.y > listeNodes[i].gsNode.playerPosition1.y)
                                {
                                    lastActionDone = availableActions[i];
                                    listeNodes.Dispose();
                                    return(i);
                                }
                            }
                        }
                        else
                        {
                            //sinon il doit tirer tout droit
                            if (listeNodes[i].gsNode.frisbeePosition.y == listeNodes[i].gsNode.playerPosition1.y)
                            {
                                lastActionDone = availableActions[i];
                                listeNodes.Dispose();
                                return(i);
                            }
                        }
                    }
                    else
                    {
                        //tirer en diagonale est la meilleure option mais on ajoute une variation pour rendre le bot moins prédictible
                        Unity.Mathematics.Random random = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, 100000));
                        float proba = random.NextFloat(0f, 3f);

                        //si proba inférieure à 1, l'agent tire tout droit
                        if (proba < 1f)
                        {
                            //il doit tirer tout droit
                            if (listeNodes[i].gsNode.frisbeePosition.y == listeNodes[i].gsNode.playerPosition1.y)
                            {
                                lastActionDone = availableActions[i];
                                return(availableActions[i]);
                            }
                        }
                        else
                        {
                            //sinon il tire en diagonale avec une variation
                            bool probaDirection = random.NextBool();

                            if (probaDirection)
                            {
                                //tir en bas
                                if (listeNodes[i].gsNode.frisbeePosition.y < listeNodes[i].gsNode.playerPosition1.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                            else
                            {
                                //tir en haut
                                if (listeNodes[i].gsNode.frisbeePosition.y > listeNodes[i].gsNode.playerPosition1.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                        }
                    }
                }
            }
        }
        else
        {
            if (!gs.isFreeze2 && gs.frisbeePosition.x > 0)
            {
                for (int i = 0; i < listeNodes.Length; i++)
                {
                    //si l'action permet d'attraper le frisbee on la sélectionne
                    if (listeNodes[i].hasFrisbee)
                    {
                        //listeNodes.Dispose();
                        return(i);
                    }
                    else
                    {
                        //si l'action réduit la distance entre le joueur et le frisbee, on conserve le résultat de cette action
                        if (listeNodes[i].getDistanceFromFrisbee() < currentDistanceFromFrisbee)
                        {
                            indexClosestToFrisbee      = i;
                            currentDistanceFromFrisbee = listeNodes[i].getDistanceFromFrisbee();
                        }
                    }
                }

                //listeNodes.Dispose();
                return(indexClosestToFrisbee);
            }
            else
            {
                //si le joueur a le frisbee, les bonnes actions sont celles qui lancent le frisbee loin de l'autre joueur
                for (int i = 0; i < listeNodes.Length; i++)
                {
                    //si le joueur a le highground, tirer tout droit est la meilleure option
                    if (highGround)
                    {
                        //tirer tout droit est la meilleure option mais on ajoute une variation pour rendre le bot moins prédictible
                        Unity.Mathematics.Random random = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, 100000));
                        float proba = random.NextFloat(0f, 3f);

                        //si proba inférieure à 1, l'agent tire en diagonale
                        if (proba < 1f)
                        {
                            bool probaDirection = random.NextBool();

                            if (probaDirection)
                            {
                                //tir en bas
                                if (listeNodes[i].gsNode.frisbeePosition.y < listeNodes[i].gsNode.playerPosition2.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                            else
                            {
                                //tir en haut
                                if (listeNodes[i].gsNode.frisbeePosition.y > listeNodes[i].gsNode.playerPosition2.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                        }
                        else
                        {
                            //sinon il doit tirer tout droit
                            if (listeNodes[i].gsNode.frisbeePosition.y == listeNodes[i].gsNode.playerPosition2.y)
                            {
                                lastActionDone = availableActions[i];
                                return(availableActions[i]);
                            }
                        }
                    }
                    else
                    {
                        //tirer en diagonale est la meilleure option mais on ajoute une variation pour rendre le bot moins prédictible
                        Unity.Mathematics.Random random = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, 100000));
                        float proba = random.NextFloat(0f, 3f);

                        //si proba inférieure à 1, l'agent tire tout droit
                        if (proba < 1f)
                        {
                            //il doit tirer tout droit
                            if (listeNodes[i].gsNode.frisbeePosition.y == listeNodes[i].gsNode.playerPosition2.y)
                            {
                                lastActionDone = availableActions[i];
                                return(availableActions[i]);
                            }
                        }
                        else
                        {
                            //sinon il tire en diagonale avec une variation
                            bool probaDirection = random.NextBool();

                            if (probaDirection)
                            {
                                //tir en bas
                                if (listeNodes[i].gsNode.frisbeePosition.y < listeNodes[i].gsNode.playerPosition2.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                            else
                            {
                                //tir en haut
                                if (listeNodes[i].gsNode.frisbeePosition.y > listeNodes[i].gsNode.playerPosition2.y)
                                {
                                    lastActionDone = availableActions[i];
                                    return(availableActions[i]);
                                }
                            }
                        }
                    }
                }
            }
        }


        return(0);
    }
Beispiel #19
0
        protected override void OnUpdate()
        {
            Debug.Log("Trying to load a level");

            var entity  = GetSingletonEntity <LevelLoadRequest>();
            var request = GetSingleton <LevelLoadRequest>();

            EntityManager.DestroyEntity(entity);
            var level   = LevelComponent.Create(request.Size, request.ChunkResolution);
            var created = EntityManager.CreateEntity();

#if UNITY_EDITOR
            EntityManager.SetName(created, "LevelInformationEntity");
#endif
            EntityManager.AddComponentData(created, level);
            EntityManager.AddComponentData(created, new Translation {
                Value = request.Position
            });
            EntityManager.AddComponentData(created, new Rotation {
                Value = request.Rotation
            });
            EntityManager.AddComponentData(created, new LocalToWorld());

            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();

            // Find the id of the sphere prefab (our player)
            var ghostId = MarchingSquaresGhostSerializerCollection.FindGhostType <VoxelGridSnapshotData>();

            // Get the prefab entity from ... server prefabs?
            chunkPrefabEntity = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;

            var random = new Unity.Mathematics.Random();
            random.InitState(1231231453);

            Entity[,] neighbours = new Entity[request.ChunkResolution, request.ChunkResolution];
            for (int y = request.ChunkResolution - 1; y >= 0; y--)
            {
                for (int x = request.ChunkResolution - 1; x >= 0; x--)
                {
                    var chunkEntity = EntityManager.Instantiate(chunkPrefabEntity);
                    neighbours[x, y] = chunkEntity;

#if UNITY_EDITOR
                    EntityManager.SetName(chunkEntity, $"Chunk_{x}_{y}");
#endif

                    Entity left = x < request.ChunkResolution - 1 ? neighbours[x + 1, y] : Entity.Null;
                    Entity up   = y < request.ChunkResolution - 1 ? neighbours[x, y + 1] : Entity.Null;
                    Entity diag = y < request.ChunkResolution - 1 && x < request.ChunkResolution - 1 ? neighbours[x + 1, y + 1] : Entity.Null;
                    EntityManager.SetComponentData(chunkEntity, new ChunkComponent
                    {
                        Size          = level.chunkSize,
                        x             = x,
                        y             = y,
                        leftNeighbour = left,
                        upNeighbour   = up,
                        diagNeighbour = diag
                    });
                    var mesh = new Mesh();
                    mesh.vertices = new Vector3[4]
                    {
                        new Vector3(0, 0, 0),
                        new Vector3(request.Size, 0, 0),
                        new Vector3(0, request.Size, 0),
                        new Vector3(1, request.Size, 0)
                    };
                    mesh.triangles = new int[6] {
                        0, 1, 2, 1, 3, 2
                    };

                    var v = new Vector3(0, 0, 1);
                    mesh.normals = new Vector3[4] {
                        v, v, v, v
                    };
                    mesh.RecalculateBounds();
                    EntityManager.AddComponentData(chunkEntity, new TriangulateTag());
                    EntityManager.AddComponentData(chunkEntity, new Parent {
                        Value = created
                    });
                    EntityManager.AddComponentData(chunkEntity, new RenderBounds {
                        Value = mesh.bounds.ToAABB()
                    });
                    EntityManager.AddComponentData(chunkEntity, new Translation {
                        Value = new float3(x * level.chunkSize, y * level.chunkSize, 0)
                    });
                    EntityManager.AddComponentData(chunkEntity, new Rotation {
                        Value = quaternion.Euler(0, 0, 0)
                    });
                    EntityManager.AddComponentData(chunkEntity, new LocalToParent());
                    EntityManager.AddComponentData(chunkEntity, new LocalToWorld());

                    EntityManager.AddSharedComponentData(chunkEntity, new RenderMesh
                    {
                        mesh                 = mesh,
                        material             = chunkMaterial,
                        needMotionVectorPass = true,
                        layer                = 0,
                        receiveShadows       = false,
                        castShadows          = UnityEngine.Rendering.ShadowCastingMode.Off,
                    });

                    var voxelBuffer = EntityManager.AddBuffer <VoxelBuffer>(chunkEntity);
                    for (int vy = 0; vy < LevelComponent.VoxelResolution; vy++)
                    {
                        for (int vx = 0; vx < LevelComponent.VoxelResolution; vx++)
                        {
                            bool st = random.NextBool();                            //(vx + vy) % 2 == 0;
                            st = true;
                            voxelBuffer.Add(new Voxel(st, vx, vy, level.voxelSize));
                        }
                    }
                }
            }
        }
Beispiel #20
0
            private CorridorComponent CreateCorridor(RoomComponent room, BoardComponent board, ref Unity.Mathematics.Random random)
            {
                var direction         = (Direction)random.NextInt(0, 4);
                var oppositeDirection = (Direction)(((int)room.EnteringCorridor + 2) % 4);

                if (random.NextInt(0, 100) > 75) //25% chance to go further from center
                {
                    var centerX = (int)math.round(board.Size.x / 2f);
                    var centerY = (int)math.round(board.Size.y / 2f);
                    if (room.X > centerX && room.Y > centerY)
                    {
                        direction = random.NextBool() ? Direction.Right : random.NextBool() ? Direction.Up : Direction.Down;
                    }
                    else if (room.X < centerX && room.Y > centerY)
                    {
                        direction = random.NextBool() ? Direction.Left : random.NextBool() ? Direction.Up : Direction.Down;
                    }
                    else if (room.X > centerX && room.Y < centerY)
                    {
                        direction = random.NextBool() ? Direction.Right : random.NextBool() ? Direction.Up : Direction.Down;
                    }
                    else
                    {
                        direction = random.NextBool() ? Direction.Left : random.NextBool() ? Direction.Up : Direction.Down;
                    }
                }

                if (direction == oppositeDirection)
                {
                    var directionInt = (int)direction;
                    directionInt++;
                    directionInt = directionInt % 4;
                    direction    = (Direction)directionInt;
                }

                var corridorLength = random.NextInt(board.MinCorridorLength, board.MaxCorridorLength);
                var corridorX      = 0;
                var corridorY      = 0;

                var maxLength = board.MaxCorridorLength;

                switch (direction)
                {
                case Direction.Up:
                    corridorX = random.NextInt(room.X, room.X + room.Size.x);
                    corridorY = room.Y + room.Size.y - 2;
                    maxLength = board.Size.y - 2 - corridorY;
                    break;

                case Direction.Left:
                    corridorX = room.X + room.Size.x - 2;
                    corridorY = random.NextInt(room.Y, room.Y + room.Size.y);
                    maxLength = board.Size.x - 2 - corridorX;
                    break;

                case Direction.Down:
                    corridorX = random.NextInt(room.X, room.X + room.Size.x + 1);
                    corridorY = room.Y;
                    maxLength = corridorY - 2;
                    break;

                case Direction.Right:
                    corridorX = room.X;
                    corridorY = random.NextInt(room.Y, room.Y + room.Size.y + 1);
                    maxLength = corridorX - 2;
                    break;
                }

                corridorLength = math.clamp(corridorLength, 0, maxLength);

                return(new CorridorComponent
                {
                    StartX = corridorX,
                    StartY = corridorY,
                    Length = corridorLength,
                    Direction = direction
                });
            }
Beispiel #21
0
        void TestTimeSystem()
        {
            // Test Data---------------------------------------------
            int batchCount = 0;

            if (Input.GetKeyDown(KeyCode.BackQuote))
            {
                batchCount = 1;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha1))
            {
                batchCount = 10;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha2))
            {
                batchCount = 100;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha3))
            {
                batchCount = 1000;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha4))
            {
                batchCount = 10000;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha5))
            {
                batchCount = 100000;
            }
            else if (Input.GetKeyDown(KeyCode.Alpha6))
            {
                batchCount = 1000000;
            }
            else if (Input.GetKey(KeyCode.Space))
            {
                batchCount = 100;
            }
            if (batchCount > 0)
            {
                if (Input.GetKey(KeyCode.X))//remove
                {
                    var _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    if (_allTime.Length > 0)
                    {
                        batchCount = math.min(_allTime.Length, batchCount);
                        var editor           = timeSystem.CreateTimeEditor();
                        var remainingIndexes = new NativeList <int>(_allTime.Length, Allocator.Temp);
                        for (int i = 0; i < _allTime.Length; i++)
                        {
                            remainingIndexes.Add(i);
                        }
                        do
                        {
                            var n = random.NextInt(remainingIndexes.Length - 1);

                            editor.ECB.DestroyEntity(_allTime[remainingIndexes[n]]);

                            remainingIndexes.RemoveAtSwapBack(n);
                        }while (--batchCount > 0);
                        remainingIndexes.Dispose();
                    }
                    _allTime.Dispose();
                }
                else if (Input.GetKey(KeyCode.Z))//change parent
                {
                    var _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    batchCount = batchCount < 2 ? 2 : batchCount;
                    if (_allTime.Length >= 2)
                    {
                        batchCount = math.min(_allTime.Length, batchCount);
                        var editor           = timeSystem.CreateTimeEditor();
                        var remainingIndexes = new NativeList <int>(_allTime.Length, Allocator.Temp);
                        for (int i = 0; i < _allTime.Length; i++)
                        {
                            remainingIndexes.Add(i);
                        }
                        do
                        {
                            var childIdx = random.NextInt(remainingIndexes.Length);
                            var child    = _allTime[remainingIndexes[childIdx]];
                            remainingIndexes.RemoveAtSwapBack(childIdx);
                            var parent = _allTime[remainingIndexes[random.NextInt(remainingIndexes.Length)]];
                            editor.SetParent(child, parent);
                        }while (--batchCount > 1);
                        remainingIndexes.Dispose();
                    }
                    _allTime.Dispose();
                }
                else if (Input.GetKey(KeyCode.E))//edit time
                {
                    var _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    if (_allTime.Length > 0)
                    {
                        batchCount = math.min(_allTime.Length, batchCount);
                        var editor           = timeSystem.CreateTimeEditor();
                        var template         = editor.EditTime(_allTime[0]).AddElapsedTime().SetTimeScale(.01f);
                        var remainingIndexes = new NativeList <int>(_allTime.Length, Allocator.Temp);
                        for (int i = 0; i < _allTime.Length; i++)
                        {
                            remainingIndexes.Add(i);
                        }
                        do
                        {
                            var n = random.NextInt(remainingIndexes.Length);
                            template.WithEntity(_allTime[remainingIndexes[n]]).ApplyBuffered(editor);
                            remainingIndexes.RemoveAtSwapBack(n);
                        }while (--batchCount > 0);
                        remainingIndexes.Dispose();
                    }
                    _allTime.Dispose();
                }
                else if (Input.GetKey(KeyCode.R))//clear parent
                {
                    var _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    if (_allTime.Length > 0)
                    {
                        batchCount = math.min(_allTime.Length, batchCount);
                        var editor           = timeSystem.CreateTimeEditor();
                        var remainingIndexes = new NativeList <int>(_allTime.Length, Allocator.Temp);
                        for (int i = 0; i < _allTime.Length; i++)
                        {
                            remainingIndexes.Add(i);
                        }
                        do
                        {
                            var n = random.NextInt(remainingIndexes.Length);
                            editor.ClearParent(_allTime[remainingIndexes[n]]);
                            remainingIndexes.RemoveAtSwapBack(n);
                        }while (--batchCount > 0);
                        remainingIndexes.Dispose();
                    }
                    _allTime.Dispose();
                }
                else if (Input.GetKey(KeyCode.C))//mixed action
                {
                    var _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    if (_allTime.Length > 0)
                    {
                        batchCount = math.min(_allTime.Length, batchCount);
                        var editor           = timeSystem.CreateTimeEditor();
                        var remainingIndexes = new NativeList <int>(_allTime.Length, Allocator.Temp);
                        for (int i = 0; i < _allTime.Length; i++)
                        {
                            remainingIndexes.Add(i);
                        }
                        do
                        {
                            var n      = remainingIndexes[random.NextInt(remainingIndexes.Length)];
                            var target = _allTime[remainingIndexes[n]];
                            remainingIndexes.RemoveAtSwapBack(n);
                            if (random.NextBool())//remove time
                            {
                                editor.ECB.DestroyEntity(target);
                            }
                            else
                            {
                                if (random.NextBool())                        //parent change
                                {
                                    if (random.NextBool() && batchCount >= 2) //set as child
                                    {
                                        var parent = _allTime[remainingIndexes[random.NextInt(remainingIndexes.Length)]];
                                        editor.SetParent(target, parent);
                                    }
                                    else //set as root
                                    {
                                        editor.ClearParent(target);
                                    }
                                }
                                if (random.NextBool())
                                {
                                    editor.EditTime(target).SetTimeScale(0.01f).ApplyBuffered(editor);
                                }
                            }
                        }while (--batchCount > 0);
                        remainingIndexes.Dispose();
                    }
                    _allTime.Dispose();
                }
                else//create time
                {
                    Entity parent   = Entity.Null;
                    var    _allTime = GetEntityQuery(ComponentType.ReadOnly <ElapsedTime>(), typeof(TimeScale), typeof(LocalTimeScale)).ToEntityArrayAsync(Allocator.TempJob, out var _allTimeJob);
                    _allTimeJob.Complete();
                    var cnt = _allTime.Length;
                    if (cnt > 0)
                    {
                        var pid = random.NextInt(cnt);
                        parent = _allTime[pid];
                    }
                    _allTime.Dispose();

                    var editor = timeSystem.CreateTimeEditor();

                    var template = editor.CreateTime().AddElapsedTime().SetTimeScale(2f * random.NextInt(1, 3), true);
                    var first    = template.ApplyBuffered(editor);
                    if (parent != Entity.Null)
                    {
                        editor.SetParent(first, parent);
                    }
                    for (int i = 1; i < batchCount; i++)
                    {
                        var cld = template.ApplyBuffered(editor);
                        editor.SetParent(cld, first);
                    }
                }
            }
            // Test Data---------------------------------------------
            if (Input.GetKeyDown(KeyCode.P))
            {
                TimeHierarchyCheck();
            }
        }
Beispiel #22
0
        void Start()
        {
            random_.InitState(1234);
            int  spawnnum = SceneManager.Num;
            bool first    = true;

            while (spawnnum > 0)
            {
                var num    = random_.NextInt(3, 5);
                var center = new float3(random_.NextFloat(-200, 200), 64f, random_.NextFloat(-200, 200));
                var replay_index_center = random_.NextInt(100, 10000);
                for (var j = 0; j < num; ++j)
                {
                    var pos          = center + random_.NextFloat3(-6, 6);
                    var replay_index = replay_index_center + random_.NextInt(20, 40) * (random_.NextBool() ? 1 : -1);
                    var entity       = FighterSystem.Instantiate(FighterManager.Prefab,
                                                                 pos,
                                                                 quaternion.identity,
                                                                 replay_index);
                    if (first)
                    {
                        var fighterSystem = World.DefaultGameObjectInjectionWorld.GetOrCreateSystem <FighterSystem>();
                        fighterSystem.PrimaryEntity = entity;
                        first = false;
                    }
                    --spawnnum;
                    if (spawnnum > 0)
                    {
                        continue;
                    }
                    break;
                }
            }
        }
Beispiel #23
0
        void generateRandomMotion(ref Random rnd, out MotionVelocity velocity, out MotionData motion, bool allowInfiniteMass)
        {
            motion = new MotionData
            {
                WorldFromMotion = generateRandomTransform(ref rnd),
                BodyFromMotion  = generateRandomTransform(ref rnd)
            };

            float3 inertia = rnd.NextFloat3(1e-3f, 100.0f);

            switch (rnd.NextInt(3))
            {
            case 0:     // all values random
                break;

            case 1:     // two values the same
                int index = rnd.NextInt(3);
                inertia[(index + 1) % 2] = inertia[index];
                break;

            case 2:     // all values the same
                inertia = inertia.zzz;
                break;
            }

            float3 nextLinVel;

            if (rnd.NextBool())
            {
                nextLinVel = float3.zero;
            }
            else
            {
                nextLinVel = rnd.NextFloat3(-50.0f, 50.0f);
            }
            float3 nextAngVel;

            if (rnd.NextBool())
            {
                nextAngVel = float3.zero;
            }
            else
            {
                nextAngVel = rnd.NextFloat3(-50.0f, 50.0f);
            }
            float3 nextInertia;
            float  nextMass;

            if (allowInfiniteMass && rnd.NextBool())
            {
                nextInertia = float3.zero;
                nextMass    = 0.0f;
            }
            else
            {
                nextMass    = rnd.NextFloat(1e-3f, 100.0f);
                nextInertia = 1.0f / inertia;
            }
            velocity = new MotionVelocity
            {
                LinearVelocity  = nextLinVel,
                AngularVelocity = nextAngVel,
                InverseInertia  = nextInertia,
                InverseMass     = nextMass
            };
        }