Esempio n. 1
0
            public void Add(int index, DynamicBuffer <VertexElement> points)
            {
                var s        = points.Length;
                var startEnd = _startEnds[_r.NextInt(_startEnds.Length)];
                var scale    = 1 - _scaleOffset + _r.NextFloat() * 2 * _scaleOffset;
                var rot      = _r.NextFloat(2 * math.PI);

                for (int i = startEnd.x; i < startEnd.y; i++)
                {
                    points.Add(Rotate(scale * _vertices[i], rot));
                }

                var min = new float2(float.MaxValue);
                var max = new float2(float.MinValue);

                for (var i = s; i < points.Length; i++)
                {
                    min = math.min(points[i], min);
                    max = math.max(points[i], max);
                }

                var size   = max - min;
                var range  = _size - size;
                var offset = _r.NextFloat2(range);

                for (var i = s; i < points.Length; i++)
                {
                    points[i] += offset - min - _size / 2;
                }
            }
        public void Convert(Entity entity, EntityManager eManager, GameObjectConversionSystem conversionSystem)
        {
            instance  = this;
            archetype = eManager.CreateArchetype(
                typeof(Position2D),
                typeof(Rotation2D),
                typeof(Scale),
                //required params
                typeof(SpriteIndex),
                typeof(SpriteSheetAnimation),
                typeof(SpriteSheetMaterial),
                typeof(SpriteSheetColor),
                typeof(SpriteMatrix),
                typeof(BufferHook)
                );

            NativeArray <Entity> entities = new NativeArray <Entity>(spriteCount, Allocator.Temp);

            eManager.CreateEntity(archetype, entities);

            //only needed for first tiem material baking
            KeyValuePair <Material, float4[]> atlasData = SpriteSheetCache.BakeSprites(sprites, "emoji");
            SpriteSheetMaterial material = new SpriteSheetMaterial {
                material = atlasData.Key
            };

            DynamicBufferManager.manager = eManager;
            DynamicBufferManager.GenerateBuffers(material, entities.Length);
            DynamicBufferManager.BakeUvBuffer(material, atlasData);

            Rect   area      = GetSpawnArea();
            Random rand      = new Random((uint)UnityEngine.Random.Range(0, int.MaxValue));
            int    cellCount = atlasData.Value.Length;

            for (int i = 0; i < entities.Length; i++)
            {
                Entity e = entities[i];
                eManager.SetComponentData(e, new SpriteIndex {
                    Value = rand.NextInt(0, cellCount)
                });
                eManager.SetComponentData(e, new Scale {
                    Value = 10
                });
                eManager.SetComponentData(e, new Position2D {
                    Value = rand.NextFloat2(area.min, area.max)
                });
                eManager.SetComponentData(e, new SpriteSheetAnimation {
                    maxSprites = cellCount, play = true, repetition = SpriteSheetAnimation.RepetitionType.Loop, samples = 10
                });
                var color            = UnityEngine.Random.ColorHSV(.15f, .75f);
                SpriteSheetColor col = new SpriteSheetColor {
                    color = new float4(color.r, color.g, color.b, color.a)
                };
                eManager.SetComponentData(e, col);
                eManager.SetComponentData(e, new BufferHook {
                    bufferID = i, bufferEnityID = DynamicBufferManager.GetEntityBufferID(material)
                });
                eManager.SetSharedComponentData(e, material);
            }
        }
    // Map generation with Worley noise
    private Map WorleyInitMap(Map map)
    {
        if (map.rows <= 0 || map.cols <= 0)
        {
            throw new Exception("Map size < 0");
        }
        // rows and cols should be odd numbers
        map.rows = (map.rows % 2) == 0 ? map.rows + 1 : map.rows;
        map.cols = (map.cols % 2) == 0 ? map.cols + 1 : map.cols;

        map.mapArray = new int[map.rows * map.cols];
        var    rnd   = new Unity.Mathematics.Random((uint)Guid.NewGuid().GetHashCode());
        float2 start = new float2(rnd.NextFloat2());

        for (int i = 0; i < map.rows; i++)
        {
            for (int j = 0; j < map.cols; j++)
            {
                float value = noise.cellular(start + new float2(i, j)).y;
                //Debug.LogFormat("noise[{0}][{1}] = {2}", i, j, value);
                map.mapArray[i * map.cols + j] = value > 0.77 ? 1 : 0;
            }
        }
        FillOutsideWall(map.mapArray, map.rows, map.cols);
        GeneratePlayerSpawnPoint(map.mapArray, map.rows, map.cols);
        return(map);
    }
    private void Spawn()
    {
        var instance = _entityManager.Instantiate(_entity);

        var random = new Random((uint)UnityEngine.Random.Range(1, 100000));

        var position    = (float3)transform.position;
        var randomPoint = random.NextFloat2(new float2(-11f, -14f), new float2(11f, 14f));

        _entityManager.SetComponentData(instance, new Translation {
            Value = position
        });
        _entityManager.SetComponentData(instance, new Rotation {
            Value = quaternion.identity
        });
        _entityManager.SetComponentData(instance, new Destination {
            Value = new float3(randomPoint.x, 0, randomPoint.y)
        });

        _entityManager.SetComponentData(instance, new MoveSpeed {
            Value = moveSpeed
        });
        _entityManager.SetComponentData(instance, new RotationSpeed {
            Value = rotationSpeed
        });
    }
Esempio n. 5
0
        void Insert()
        {
            var p     = Prefabs[_r.NextInt(Prefabs.Length)];
            var scale = 1 - ScaleOffset + _r.NextFloat() * 2 * ScaleOffset;
            var rot   = _r.NextFloat(2 * math.PI);

            _points.Clear();
            foreach (var f in p.Vertices)
            {
                _points.Add(DemoMath.Rotate(scale * f, rot));
            }

            var min = new float2(float.MaxValue);
            var max = new float2(float.MinValue);

            for (var i = 0; i < _points.Count; i++)
            {
                min = math.min(_points[i], min);
                max = math.max(_points[i], max);
            }

            var size   = max - min;
            var range  = (float2)Plane.Size - size;
            var offset = _r.NextFloat2(range);

            for (var i = 0; i < _points.Count; i++)
            {
                _points[i] += (Vector2)(offset - min - (float2)Plane.Size / 2);
            }

            _ids.Add(Plane.InsertObstacle(_points));
        }
    void SetManualTrees(int nTrees)
    {
        // int nTrees = 2000000;
        Unity.Mathematics.Random random = new Unity.Mathematics.Random(1);

        for (int i = 0; i < treeManualPrefabs.Length; i++)
        {
            List <float3> treeInstances = new List <float3>();
            for (int j = 0; j < nTrees; j++)
            {
                float2 pos       = random.NextFloat2();
                float  treeBiome = NoiseExtensions.SNoise(pos, 1f, 2f, 0.5f, 1, 5f, new float2(10000, 0));

                if (treeBiome < 0.8f)
                {
                    float height = terrain.SampleHeight(new float3((pos.x - 0.5f) * size, 0f, (pos.y - 0.5f) * size));
                    if (height > 337f)
                    {
                        treeInstances.Add(
                            new float3(
                                (pos.x - 0.5f) * size,
                                height,
                                (pos.y - 0.5f) * size
                                )
                            );
                    }
                }
            }

            BillboardsManager.active.UpdatePositions(treeManualPrefabs[i], treeInstances.ToArray());
        }
    }
Esempio n. 7
0
        void Insert()
        {
            var obstacle = ObstaclePrefabs[_r.NextInt(ObstaclePrefabs.Length)];
            var scale    = ObstacleMinScale + _r.NextFloat() * ObstacleScaleRange;
            var rot      = _r.NextFloat(2 * math.PI);
            var vertices = obstacle.Vertices.Select(f => DemoMath.Rotate(scale * f, rot)).ToList();

            var min = new float2(float.MaxValue);
            var max = new float2(float.MinValue);

            for (var i = 0; i < vertices.Count; i++)
            {
                min = math.min(vertices[i], min);
                max = math.max(vertices[i], max);
            }

            var size   = max - min;
            var range  = _size - new float2(0, 2 * SpawnRectHeight) - size;
            var offset = _r.NextFloat2(range) + new float2(0, SpawnRectHeight) - _size / 2;

            for (var i = 0; i < vertices.Count; i++)
            {
                vertices[i] += (Vector2)(offset - min);
            }

            Plane.InsertObstacle(vertices);
        }
Esempio n. 8
0
    public static float2[] GeneratePoints(int count, ref Random random, Func <float2, float> density = null, Func <float2, float> envelope = null, Action <string> progressCallback = null)
    {
        if (density == null)
        {
            density = v => .5f;
        }
        if (envelope == null)
        {
            envelope = v => 1;
        }
        var inputSamples = new float2[count * 8];
        var sample       = 0;
        var accumulator  = 0f;

        while (sample < inputSamples.Length)
        {
            var v = random.NextFloat2();
            accumulator += pow(saturate(density(v)), 2f) * saturate(envelope(v));
            if (accumulator > .5f)
            {
                accumulator            = 0;
                inputSamples[sample++] = v;
                progressCallback?.Invoke($"Generating Samples: {sample} / {inputSamples.Length}");
            }
        }
        var outputSamples = new float2[count];

        progressCallback?.Invoke("Eliminating Samples");
        Eliminate(inputSamples, outputSamples, density);
        return(outputSamples);
    }
Esempio n. 9
0
                public unsafe void GenerateBezier()
                {
                    var points = new List <Vector2>(100);
                    var seed   = (uint)1;
                    var random = new Unity.Mathematics.Random(seed);

                    for (int i = 0; i < 100; i++)
                    {
                        points.Add(random.NextFloat2());
                    }

                    var original = new OPCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);

                    for (int i = 0; i < points.Count; i++)
                    {
                        original.AddPoint(points[i]);
                    }

                    var tanL = original.GetLeftTangent(original._pts.Count);
                    var tanR = original.GetRightTangent(original._first);

                    var optimizedPts = new List <Vector2>();

                    for (int i = 0; i < original._pts.Count; i++)
                    {
                        optimizedPts.Add(original._pts[i]);
                    }

                    var optimizedU = new List <float>();

                    for (int i = 0; i < original._u.Count; i++)
                    {
                        optimizedU.Add(original._u[i]);
                    }

                    CubicBezier originalBezier;

                    using (original._pts.ViewAsNativeArray(out var pts))
                        using (original._u.ViewAsNativeArray(out var u))
                            OptimizedHelpers.GenerateBezierStandard(0, original._pts.Count, tanL, tanR, (Vector2 *)pts.GetUnsafePtr(), (float *)u.GetUnsafePtr(), out originalBezier);

                    CubicBezier optimizedBezier;

                    using (optimizedPts.ViewAsNativeArray(out var pts))
                        using (optimizedU.ViewAsNativeArray(out var u))
                            OptimizedHelpers.GenerateBezierV256V1(0, original._pts.Count, tanL, tanR, (Vector2 *)pts.GetUnsafePtr(), (float *)u.GetUnsafePtr(), out optimizedBezier);

                    for (int i = 0; i < original._pts.Count; i++)
                    {
                        Assert.IsTrue(math.all(aprox(original._pts[i], optimizedPts[i])));
                    }

                    for (int i = 0; i < original._u.Count; i++)
                    {
                        Assert.IsTrue(aprox(original._u[i], optimizedU[i]));
                    }

                    Assert.IsTrue(Equals(originalBezier, optimizedBezier));
                }
    protected override void OnUpdate()
    {
        EntityQueryBuilder queryBuilder = Entities.WithAll(typeof(MoveComponent), typeof(EnemyComponent));

        queryBuilder.ForEach((ref MoveComponent moveComponent, ref EnemyComponent enemyComponent) => {
            moveComponent.dragDir = rand.NextFloat2(1) - 0.5f;
        });
    }
        public void Convert(Entity entity, EntityManager eManager, GameObjectConversionSystem conversionSystem)
        {
            EntityArchetype archetype = eManager.CreateArchetype(
                typeof(Position2D),
                typeof(Rotation2D),
                typeof(Scale),
                //required params
                typeof(SpriteIndex),
                typeof(SpriteSheetAnimation),
                typeof(SpriteSheetMaterial),
                typeof(SpriteSheetColor),
                typeof(SpriteMatrix),
                typeof(BufferHook)
                );

            NativeArray <Entity> entities = new NativeArray <Entity>(spriteCount, Allocator.Temp);

            eManager.CreateEntity(archetype, entities);

            //only needed for the first time to bake the material and create the uv map
            SpriteSheetManager.RecordSpriteSheet(sprites, spriteSheetName, entities.Length);


            Rect   area                  = GetSpawnArea();
            Random rand                  = new Random((uint)UnityEngine.Random.Range(0, int.MaxValue));
            int    cellCount             = SpriteSheetCache.GetLength(spriteSheetName);
            SpriteSheetMaterial material = new SpriteSheetMaterial {
                material = SpriteSheetCache.GetMaterial(spriteSheetName)
            };

            for (int i = 0; i < entities.Length; i++)
            {
                Entity e = entities[i];
                eManager.SetComponentData(e, new SpriteIndex {
                    Value = rand.NextInt(0, cellCount)
                });
                eManager.SetComponentData(e, new Scale {
                    Value = 10
                });
                eManager.SetComponentData(e, new Position2D {
                    Value = rand.NextFloat2(area.min, area.max)
                });
                eManager.SetComponentData(e, new SpriteSheetAnimation {
                    frameCount = cellCount, playMode = PlayMode.Loop, framesPerSecond = 10
                });
                var color            = UnityEngine.Random.ColorHSV(.15f, .75f);
                SpriteSheetColor col = new SpriteSheetColor {
                    color = new float4(color.r, color.g, color.b, color.a)
                };
                eManager.SetComponentData(e, col);
                eManager.SetComponentData(e, new BufferHook {
                    bufferID = i, bufferEntityID = DynamicBufferManager.GetEntityBufferID(material)
                });
                eManager.SetSharedComponentData(e, material);
            }
        }
        public float2 NextFloat2()
        {
            float2 s;

            do
            {
                s = _uniform.NextFloat2();
            }while (s.x <= epsilon);//happens rarely but 0 breaks log

            return(sqrt(-2.0f * log(s.x)) * new float2(cos(tau * s.y), sin(tau * s.y)));
        }
Esempio n. 13
0
        public void ComputeAreaOfTriangle_IgnoresTranslations(float area, Vector2[] triangle)
        {
            var translation = m_Rand.NextFloat2();

            for (var i = 0; i < 3; i++)
            {
                triangle[i] = (Vector2)translation + triangle[i];
            }
            Assert.AreApproximatelyEqual(area,
                                         ObjectPlacementUtilities.ComputeAreaOfTriangle(triangle[0], triangle[1], triangle[2]));
        }
Esempio n. 14
0
    ////

    Boid spawn(ref Unity.Mathematics.Random rand, float2 SpawnRect)
    {
        return(new Boid {
            pos = rand.NextFloat2() * SpawnRect,
            vel = rand.NextFloat2Direction() * rand.NextFloat() * 0.2f * SpeedTarget,
            forward = float2(0, 1),
            //size = (rand.NextFloat() + 0.8f) * BoidSize,
            size = BoidSize,

            color = BoidColors.Evaluate(rand.NextFloat()),
        });
    }
Esempio n. 15
0
        private void UpdateData()
        {
            float4x4 localToWorldMatrix     = transform.localToWorldMatrix;
            float4x4 normalizedLocalToWorld = float4x4(float4(transform.right * localScale.x, 0), float4(transform.up * localScale.y, 0), float4(transform.forward * localScale.z, 0), float4(transform.position, 1));

            allMatrices.Clear();
            for (int x = 0; x < countPerFrame.x; ++x)
            {
                for (int y = 0; y < countPerFrame.y; ++y)
                {
                    for (int z = 0; z < countPerFrame.z; ++z)
                    {
                        float3 uv       = (float3(x, y, z) + 0.5f) / float3(countPerFrame);
                        float3 localPos = lerp(-0.5f, 0.5f, uv);
                        allMatrices.Add(float4x4(normalizedLocalToWorld.c0, normalizedLocalToWorld.c1, normalizedLocalToWorld.c2, mul(localToWorldMatrix, float4(localPos, 1))));
                    }
                }
            }

            Random r = new Random(RandomSeed);

            if (allMatrices.Length > tileOffsets.Length)
            {
                for (int i = tileOffsets.Length; i < allMatrices.Length; ++i)
                {
                    float tile = (r.NextFloat() * (uvTileRandomRange.y - uvTileRandomRange.x)) + uvTileRandomRange.x;
                    tileOffsets.Add(float4(tile, tile, r.NextFloat2() * (uvOffsetRandomRange.y - uvOffsetRandomRange.x) + uvOffsetRandomRange.x));
                }
            }
            else if (allMatrices.Length < tileOffsets.Length)
            {
                tileOffsets.RemoveLast(tileOffsets.Length - allMatrices.Length);
            }
            NativeArray <PerObjectDatas> datas = new NativeArray <PerObjectDatas>(tileOffsets.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
            PerObjectDatas *ptr = datas.Ptr();

            for (int i = 0; i < tileOffsets.Length; ++i)
            {
                ptr[i] = new PerObjectDatas
                {
                    localToWorldMatrix = allMatrices[i],
                    uvTileOffset       = tileOffsets[i]
                };
            }
            if (datas.Length > instanceBuffer.count)
            {
                instanceBuffer.Dispose();
                instanceBuffer = new ComputeBuffer(datas.Length, sizeof(PerObjectDatas));
            }
            instanceBuffer.SetData(datas);
            datas.Dispose();
        }
        public void Execute(
            [ReadOnly] ref Translation translation,
            ref Destination destination)
        {
            var distance = math.distance(translation.Value, destination.Value);

            if (distance <= 1)
            {
                var randomPoint = Random.NextFloat2(new float2(-11f, -14f), new float2(11f, 14f));

                destination.Value = new float3(randomPoint.x, 0, randomPoint.y);
            }
        }
Esempio n. 17
0
        private float2 GetPointInSpawnZone()
        {
            float2 rngPoint;
            var    reps = 0;

            do
            {
                rngPoint = rNg.NextFloat2(bounds.Ul, bounds.Lr);
                reps++;
            } while (IsPointNearCamera(rngPoint) && reps < 5);

            return(rngPoint);
        }
    void SetBuildInTrees(int nTrees)
    {
        // Tree prototypes
        TreePrototype[] treePrototypes = new TreePrototype[treeBuildInPrefabs.Length];
        for (int i = 0; i < treePrototypes.Length; i++)
        {
            treePrototypes[i] = new TreePrototype()
            {
                prefab     = treeBuildInPrefabs[i],
                bendFactor = 0.1f
            };
        }
        terrainData.treePrototypes = treePrototypes;

        // Tree instances
        List <TreeInstance> treeInstances = new List <TreeInstance>();

        Unity.Mathematics.Random random = new Unity.Mathematics.Random(1);

        for (int i = 0; i < treeBuildInPrefabs.Length; i++)
        {
            for (int j = 0; j < nTrees; j++)
            {
                float2 pos       = random.NextFloat2();
                float  treeBiome = NoiseExtensions.SNoise(pos, 1f, 2f, 0.5f, 1, 5f, new float2(10000, 0));

                if (treeBiome < 0.8f)
                {
                    float height = terrain.SampleHeight(new float3((pos.x - 0.5f) * size, 0f, (pos.y - 0.5f) * size));
                    if (height > 337f)
                    {
                        treeInstances.Add(
                            new TreeInstance()
                        {
                            color          = Color.white,
                            heightScale    = 1f,
                            lightmapColor  = Color.white,
                            position       = new float3(pos.x, height / maxHeight, pos.y),
                            prototypeIndex = i,
                            widthScale     = 1f
                        }
                            );
                    }
                }
            }
        }
        terrainData.treeInstances = treeInstances.ToArray();


        terrain.treeDistance = size;
    }
Esempio n. 19
0
    // Start is called before the first frame update
    void Start()
    {
        Points = new List <Vector2>(PointCount);
        //Seed = (uint)Mathf.Max(1, System.DateTime.Now.Millisecond);
        var random = new Unity.Mathematics.Random(Seed);

        for (int i = 0; i < PointCount; i++)
        {
            Points.Add(random.NextFloat2());
        }
        //for (int i = 0; i < PointCount; i++)
        //{
        //    Points.Add(new Vector2(i / 100.0f, Mathf.Sin(i / 10.0f)));
        //}

        {
            var s = new BMCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);
            for (int i = 0; i < Points.Count; i++)
            {
                s.AddPoint(Points[i]);
            }

            var curves = s.Curves;
            BurningMimeCurves.positionCount = curves.Count * 4;
            for (int i = 0; i < curves.Count; i++)
            {
                BurningMimeCurves.SetPosition(i * 4 + 0, curves[i].p0 * 25.0f);
                BurningMimeCurves.SetPosition(i * 4 + 1, curves[i].p1 * 25.0f);
                BurningMimeCurves.SetPosition(i * 4 + 2, curves[i].p2 * 25.0f);
                BurningMimeCurves.SetPosition(i * 4 + 3, curves[i].p3 * 25.0f);
            }
        }

        {
            var s = new OPCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);
            for (int i = 0; i < Points.Count; i++)
            {
                s.AddPoint(Points[i]);
            }

            var curves = s.Curves;
            OptimizedCurves.positionCount = curves.Count * 4;
            for (int i = 0; i < curves.Count; i++)
            {
                OptimizedCurves.SetPosition(i * 4 + 0, curves[i].p0 * 25.0f);
                OptimizedCurves.SetPosition(i * 4 + 1, curves[i].p1 * 25.0f);
                OptimizedCurves.SetPosition(i * 4 + 2, curves[i].p2 * 25.0f);
                OptimizedCurves.SetPosition(i * 4 + 3, curves[i].p3 * 25.0f);
            }
        }
    }
Esempio n. 20
0
    //randomly place a couple of autorophs
    void TestAutotrophs()
    {
        var  settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        var  entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        uint seed          = 15;

        Random random = new  Random(seed);

        for (int i = 0; i < 9; i++)
        {
            var instance = entityManager.CreateEntity();
            var pos      = random.NextFloat2();
            entityManager.AddComponentData(instance, new PosXY()
            {
                Value = pos
            });
            entityManager.AddComponentData(instance, new FoodEnergy {
                Value = 0
            });
            entityManager.AddComponentData(instance, new GrowSpeed {
                Value = 0.5f
            });

            var rect = new float4();
            rect[0] = (math.floor(pos.x * size.x)) / size.x;
            rect[2] = rect[0] + 1.0f / size.x;
            rect[1] = (math.floor(pos.y * size.y)) / size.y;
            rect[3] = rect[1] + 1.0f / size.y;
            entityManager.AddSharedComponentData(instance, new Cell {
                rect = rect
            });

            /*
             * entityManager.AddChunkComponentData<CellEnergyChunk>(instance);
             * var entityChunk = entityManager.GetChunk(instance);
             * entityManager.SetChunkComponentData<CellEnergyChunk>(entityChunk,
             *  new CellEnergyChunk(){Value = 0f});
             */
        }
        EntityQueryDesc ChunksWithoutCellEnergyChunkDesc = new EntityQueryDesc()
        {
            None = new ComponentType[] { ComponentType.ChunkComponent <CellEnergyChunk>() }
        };
        var ChunksWithoutCellEnergyChunk = entityManager.CreateEntityQuery(ChunksWithoutCellEnergyChunkDesc);

        entityManager.AddChunkComponentData <CellEnergyChunk>(ChunksWithoutCellEnergyChunk,
                                                              new CellEnergyChunk()
        {
            Value = 0F
        });
    }
Esempio n. 21
0
        public override void UpdateSettings()
        {
            if (!enabled)
            {
                return;
            }
            Random r = new Random(RandomSeed);

            for (int i = 0; i < tileOffsets.Length; ++i)
            {
                float tile = (r.NextFloat() * (uvTileRandomRange.y - uvTileRandomRange.x)) + uvTileRandomRange.x;
                tileOffsets[i] = (float4(tile, tile, r.NextFloat2() * (uvOffsetRandomRange.y - uvOffsetRandomRange.x) + uvOffsetRandomRange.x));
            }
            matIndex = r.NextUInt();
        }
Esempio n. 22
0
        public void Execute(int index)
        {
            if (randomInit)
            {
                random     = new Unity.Mathematics.Random((uint)threadIndex);
                randomInit = false;
            }

            Entity e   = ecb.CreateEntity(index, archetype);
            float2 pos = random.NextFloat2(posMin, posMax);

            ecb.SetComponent <Position>(index, e, new Position {
                pos = pos
            });
        }
Esempio n. 23
0
    private void VoronoiGeneration(TerrainData _data)
    {
        float maxX = _data.size.x;
        float maxY = _data.size.y;

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

        float2[] centroids = new float2[m_centroidAmount];
        for (int i = 0; i < m_centroidAmount; ++i)
        {
            centroids[i] = rand.NextFloat2(new float2(maxX, maxY));

            Debug.Log(centroids[i]);
        }

        // Foreach unit of space, get closest centroid.
    }
            private NativeArray <float3> GeneratePointsInCircle(int count, float3 center, float radius)
            {
                var points = new NativeArray <float3>(count, Allocator.Temp);
                var seed   = (uint)math.abs(math.ceil(center.x + center.y)) + 10;
                var random = new Random(seed);

                for (int i = 0; i < count; i++)
                {
                    var point = 2f * random.NextFloat2() - 1f;
                    point *= radius;
                    point += new float2(center.x, center.y);

                    points[i] = new float3(point.x, point.y, 0);
                }

                return(points);
            }
Esempio n. 25
0
        public void PostConstruct()
        {
            _biomeDefs            = BiomeDefs.BiomeDefData;
            _terrainCurvesSampled = BiomeDefs.TerrainCurvesSampled;
            _lodes          = BiomeDefs.Lodes;
            _lodeThresholds = BiomeDefs.LodeThresholds;

            //generate octave offsets
            var random = new Random();

            random.InitState(928349238); // TODO fill with seed
            _offsets    = new NativeArray <float2>(GeometryConsts.MAX_OCTAVES, Allocator.Persistent);
            _offsets[0] = 0;
            for (var i = 1; i < GeometryConsts.MAX_OCTAVES; i++)
            {
                _offsets[i] = random.NextFloat2(-1f, 1f);
            }
        }
Esempio n. 26
0
                [Explicit("Test for specific fail case which I don't want to deal with atm, so keeping it around here, but will have fix for it at some point?")] // TODO: Make this pass
                public void FailingAddTrianglePoints()
                {
                    //var randomSeed = (uint)Mathf.Max(1, System.DateTime.Now.Millisecond);
                    var randomSeed = (uint)886;

                    try
                    {
                        using var d = new Unity.Profiling.ProfilerMarker("AddTrianglePoints").Auto();
                        var points       = new List <Vector2>();
                        var randomPoints = new Unity.Mathematics.Random(randomSeed);
                        for (int i = 0; i < 500; i++)
                        {
                            points.Add(randomPoints.NextFloat2());
                        }

                        var desiredSpline   = new BMCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);
                        var optimizedSpline = new OPCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);
                        for (int i = 0; i < points.Count; i++)
                        {
                            var desiredRes   = desiredSpline.AddPoint(points[i]);
                            var optimizedRes = optimizedSpline.AddPoint(points[i]);
                            Assert.IsTrue(desiredRes.FirstChangedIndex == optimizedRes.FirstChangedIndex);
                        }

                        for (int i = 0; i < desiredSpline.Curves.Count; i++)
                        {
                            try
                            {
                                Assert.IsTrue(Equals(desiredSpline.Curves[i], optimizedSpline.Curves[i]));
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError($"Seed: {randomSeed}");
                        throw e;
                    }
                }
Esempio n. 27
0
    void PlotRingPoints(float yAngle, int yIndex)
    {
        float ringRadius = radius * math.sin(yAngle);
        float xIncrement = (pointDistance / ringRadius) / math.PI;
        int   pointCount = (int)(math.PI * 2 / xIncrement);

        worldOffset[yIndex]  = new float3[pointCount];
        radianOffset[yIndex] = new float2[pointCount];

        for (int i = 0; i < pointCount; i++)
        {
            float  xAngle = AngleInRadians(xIncrement, i);
            float2 offset = new float2(xAngle, yAngle);
            offset += random.NextFloat2(0, jitter);
            radianOffset[yIndex][i] = offset;

            float3 position = PositionOnSphere(offset);
            worldOffset[yIndex][i] = position;
        }
    }
Esempio n. 28
0
            public void RepeatableSingleLargeTest()
            {
                var points = new List <Vector2>(PointCount);
                var seed   = (uint)1;
                var random = new Unity.Mathematics.Random(seed);

                for (int i = 0; i < PointCount; i++)
                {
                    points.Add(random.NextFloat2());
                }

                using var total = OPTotal.Auto();
                var s = new OPCurves.CurveBuilder(DistanceBetweenPoints, CurveSplitError);

                using var addPoints = OPAddPoints.Auto();
                for (int i = 0; i < points.Count; i++)
                {
                    s.AddPoint(points[i]);
                }
            }
        public static Entity SpawnEntity(EntityCommandBuffer eManager, string materialName)
        {
            var e = eManager.CreateEntity(instance.archetype);
            //only needed for first tiem material baking
            Material material = SpriteSheetCache.materialNameMaterial[materialName];

            int    bufferID   = DynamicBufferManager.AddDynamicBuffers(DynamicBufferManager.GetEntityBuffer(material), material);
            Entity uvBuffer   = DynamicBufferManager.GetEntityBuffer(material);
            int    maxSprites = DynamicBufferManager.manager.GetBuffer <UvBuffer>(uvBuffer).Length;

            Rect   area = instance.GetSpawnArea();
            Random rand = new Random((uint)UnityEngine.Random.Range(0, int.MaxValue));

            eManager.SetComponent(e, new SpriteIndex {
                Value = 0
            });
            eManager.SetComponent(e, new Scale {
                Value = 20
            });
            eManager.SetComponent(e, new Position2D {
                Value = rand.NextFloat2(area.min, area.max)
            });
            eManager.SetComponent(e, new SpriteSheetAnimation {
                maxSprites = maxSprites, play = true, repetition = SpriteSheetAnimation.RepetitionType.Loop, samples = 10
            });
            var color            = UnityEngine.Random.ColorHSV(.15f, .75f);
            SpriteSheetColor col = new SpriteSheetColor {
                color = new float4(color.r, color.g, color.b, color.a)
            };

            eManager.SetComponent(e, col);
            var spriteSheetMaterial = new SpriteSheetMaterial {
                material = material
            };

            eManager.SetComponent(e, new BufferHook {
                bufferID = bufferID, bufferEnityID = DynamicBufferManager.GetEntityBufferID(spriteSheetMaterial)
            });
            eManager.SetSharedComponent(e, spriteSheetMaterial);
            return(e);
        }
Esempio n. 30
0
    void Update()
    {
        ClearBuffer(inputBuffer);

        if (random.NextInt(1000) < 100)
        {
            var impulse = random.NextFloat2();
            inputBuffer[(int)(impulse.y * MESH_RANGE) * MESH_RANGE + (int)(impulse.x * MESH_RANGE)] = 1f;
        }

        var prevBuf = activeBuffer == 0 ? waveBuffer0 : waveBuffer1;
        var curBuf  = activeBuffer == 0 ? waveBuffer1 : waveBuffer0;

        UnityEngine.Profiling.Profiler.BeginSample("DoWave");
        DoWave(inputBuffer, prevBuf, curBuf);
        UnityEngine.Profiling.Profiler.EndSample();

        ApplyWave(m_Mesh, m_Vertices, curBuf);

        activeBuffer = 1 - activeBuffer;
    }