コード例 #1
0
        public void ByteConversion_Vector3_Int()
        {
            var value    = new Vector3(1.0f, 2.0f, 3.0f);
            var bytes    = new byte[VectorExtension.ByteSizeVector3];
            var newValue = value;

            using (var memoryStream = new MemoryStream(bytes))
            {
                using (var binaryWriter = new BinaryWriter(memoryStream))
                {
                    value.ToBytesInt(binaryWriter);
                    Assert.AreEqual(VectorExtension.ByteSizeVector3, memoryStream.Position);

                    binaryWriter.Seek(0, SeekOrigin.Begin);

                    using (var binaryReader = new BinaryReader(memoryStream))
                    {
                        newValue = VectorExtension.ToVector3Int(binaryReader);
                        Assert.AreEqual(VectorExtension.ByteSizeVector3, memoryStream.Position);
                    }
                }
            }

            Assert.AreEqual(value, newValue);
        }
コード例 #2
0
        protected void ApplyBuildGenericTrianglesForChunkProperties(ComputeShader forShader, CompressedMarchingCubeChunk chunk, int numTris)
        {
            bool storeMinDegree = chunk.MinDegreeBuffer != null;

            forShader.SetBool("storeMinDegrees", storeMinDegree);

            if (storeMinDegree)
            {
                forShader.SetBuffer(0, "minDegreeAtCoord", chunk.MinDegreeBuffer);
            }
            else
            {
                forShader.SetBuffer(0, "minDegreeAtCoord", ChunkGPUDataRequest.emptyMinDegreeBuffer);
            }

            Vector4 anchor        = VectorExtension.ToVector4(chunk.AnchorPos);
            int     pointsPerAxis = chunk.NoisePointsPerAxis;

            forShader.SetVector("anchor", anchor);
            forShader.SetFloat("spacing", chunk.LOD);
            forShader.SetInt("numPointsPerAxis", pointsPerAxis);
            forShader.SetInt("length", numTris);

            forShader.SetInt("pointSpacing", chunk.PointSpacing);
        }
コード例 #3
0
        private Dictionary <PointInt, double> _getMoveRanks(double[,] map, KeyValuePair <WaterDrop, PointInt> drop)
        {
            var currentDropPosition = drop.Value;
            var dropObj             = drop.Key;
            var moveRanks           = new Dictionary <PointInt, double>();

            foreach (var targetCell in _neighborsGetter(currentDropPosition))
            {
                if (!IsInMap(map, targetCell))
                {
                    continue;
                }
                var heightDiff = GetHeight(map, currentDropPosition) - GetHeight(map, targetCell);
                if (heightDiff < 0)
                {
                    continue;
                }
                if (dropObj.Speed.Length > 0)
                {
                    var targetSpeed = VectorExtension.CreateFromTwoPoints(currentDropPosition, targetCell);
                    var angle       = dropObj.Speed.GetAngleWith(targetSpeed);
                    var factor      = 0.5 * Math.Abs(angle);
                    moveRanks[targetCell] = heightDiff / factor;
                }
                else
                {
                    var factor = Math.PI / 3; //TODO
                    moveRanks[targetCell] = heightDiff / factor;
                }
            }

            return(moveRanks);
        }
コード例 #4
0
        public void BuildNeighbourChunks(bool[] dirs, int chunkSize, Vector3Int centerPos)
        {
            Vector3Int v3;
            int        count = dirs.Length;

            for (int i = 0; i < count; ++i)
            {
                if (!dirs[i])
                {
                    continue;
                }

                v3 = VectorExtension.DirectionFromIndex[i] * (chunkSize + 1) + centerPos;
                float sqrDist = (startPos - v3).sqrMagnitude;

                if (sqrDist <= buildAroundSqrDistance &&
                    !chunkGroup.HasGroupItemAt(VectorExtension.ToArray(v3)))
                {
                    closestNeighbours.Enqueue(sqrDist, v3);
                }
                else
                {
                    BuildEmptyChunkAt(v3);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Used to initialize the ViewModel and its properties
        /// </summary>
        public void ConstructViewModel()
        {
            // If model was not initailized properly, get Model from GameManager
            if (model == null)
            {
                model = GameManager.instance.model;
            }


            // Initialize Properties

            mGameSquares = new ObservableList <GameSquare>(
                VectorExtension.GetRectangularPositions(model.Columns, model.Rows)
                .Select(pos => new GameSquare()
            {
                Position = pos,
                Unit     = model.GetUnitAtPosition(pos),
                Tile     = model.GetTileAtPosition(pos),
            })
                );

            mUnitViewModels = new ObservableList <UnitViewModel>(
                model.Players.SelectMany(player => player.Units)
                .Select(unit => new UnitViewModel(unit)));
            CombatMode = false;
        }
コード例 #6
0
        public IEnumerator BuildRelevantChunksParallelAround(IMarchingCubeChunk chunk)
        {
            bool[] dirs  = chunk.HasNeighbourInDirection;
            int    count = dirs.Length;

            for (int i = 0; i < count; ++i)
            {
                if (!dirs[i])
                {
                    continue;
                }

                Vector3Int v3 = VectorExtension.GetDirectionFromIndex(i) * (chunk.ChunkSize + 1) + chunk.CenterPos;
                closestNeighbours.Enqueue(0, v3);
            }
            if (closestNeighbours.size > 0)
            {
                yield return(BuildRelevantChunksParallelAround());
            }

            watch.Stop();
            Debug.Log("Total millis: " + watch.Elapsed.TotalMilliseconds);
            if (totalTriBuild >= maxTrianglesLeft)
            {
                Debug.Log("Aborted");
            }
            Debug.Log("Total triangles: " + totalTriBuild);
        }
コード例 #7
0
        //TODO: When editing chunk that spawns new chunk build neighbours of new chunk if existing
        public void RebuildAround(Vector3 offset, int radius, Vector3Int clickedIndex, float delta)
        {
            ///define loop ranges
            Vector3Int start;
            Vector3Int end;

            GetNoiseEditData(offset, radius, VectorExtension.ToVector3Int(clickedIndex - offset), out start, out end);

            bool rebuildChunk;

            if (!HasPoints)
            {
                ChunkHandler.RequestNoiseForChunk(this);
            }
            rebuildChunk = EditPointsOnCPU(start, end, clickedIndex + offset, radius, delta);

            //else
            //{
            //    rebuildChunk = true;
            //    ChunkHandler.SetEditedNoiseAtPosition(this, clickedIndex + offset, start,end,delta,radius);
            //}

            if (rebuildChunk)
            {
                //System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();
                //w.Start();
                StoreChunkState();
                storageLeaf.RemoveMipMapInHirachy();
                RebuildFromNoiseAroundOnGPU(start, end, clickedIndex, radius);
                //RebuildFromNoiseAround(start, end, clickedIndex, radius);
                //w.Stop();
                //Debug.Log("Time for rebuild only: " + w.Elapsed.TotalMilliseconds);
            }
        }
コード例 #8
0
        private static Vector CalculateSpeed(double[,] map, KeyValuePair <WaterDrop, PointInt> drop, KeyValuePair <PointInt, double> targetCell)
        {
            var scalarSpeed     = GetHeight(map, drop.Value) - GetHeight(map, targetCell.Key);
            var unitVectorSpeed = VectorExtension.CreateFromTwoPoints(drop.Value, targetCell.Key);
            var speed           = scalarSpeed * unitVectorSpeed;

            return(speed + drop.Key.Speed);
        }
コード例 #9
0
        protected IEnumerator WaitTillAsynGenerationDone()
        {
            Time.timeScale  = 0;
            mainCam.enabled = false;

            bool             repeat = true;
            List <Exception> x      = CompressedMarchingCubeChunk.xs;

            while (repeat)
            {
                Vector3 next;
                bool    isNextInProgress;


                if (totalTriBuild < maxTrianglesLeft)
                {
                    //TODO: while waiting create mesh displayers! -> leads to worse performance?
                    while (finishedNeighbourTasks.Count > 0)
                    {
                        ChunkNeighbourTask task = GetFinishedTask();
                        BuildNeighbourChunks(task);
                    }
                }

                while (closestNeighbours.size > 0)
                {
                    do
                    {
                        next             = closestNeighbours.Dequeue();
                        isNextInProgress = chunkGroup.HasChunkStartedAt(VectorExtension.ToArray(next));
                    } while (isNextInProgress && closestNeighbours.size > 0);

                    if (!isNextInProgress)
                    {
                        CreateChunkWithAsyncGPUReadback(next, FindNeighbourOfChunk);
                    }
                }

                if (neighbourFinder.InitializationDone)
                {
                    repeat          = false;
                    Time.timeScale  = 1;
                    mainCam.enabled = true;

                    watch.Stop();
                    Debug.Log("Total millis: " + watch.Elapsed.TotalMilliseconds);
                    if (totalTriBuild >= maxTrianglesLeft)
                    {
                        Debug.Log("Aborted");
                    }
                    Debug.Log("Total triangles: " + totalTriBuild);
                    StartCoroutine(CreateEmptyChunks());
                    OnInitialializationDone();
                }
                yield return(null);
            }
        }
コード例 #10
0
        //TODO:Check if collider can be removed from most chunks.
        //Collision can be approximated by calling noise function for lowest point of object and checking if its noise is larger than surface value

        protected IMarchingCubeChunk CreateChunkAt(Vector3 pos, Vector3Int coord, bool allowOverride = false)
        {
            int  lodPower;
            int  chunkSizePower;
            bool careForNeighbours;

            GetSizeAndLodPowerForChunkPosition(pos, out chunkSizePower, out lodPower, out careForNeighbours);
            return(CreateChunkWithProperties(VectorExtension.ToVector3Int(pos), coord, lodPower, chunkSizePower, careForNeighbours, allowOverride));
        }
コード例 #11
0
        public void GetDistancePointTest_ThrowsMatrixDotNetException()
        {
            // Arrange
            Vector <int> v1 = new[] { 4, 2, 1, 5 };
            Vector <int> v2 = new[] { 4, 2, 4 };

            // Act Assert
            Assert.Throws <SizeNotEqualException>(() => VectorExtension.GetDistancePoint(v1, v2));
        }
コード例 #12
0
 public void ApplyPrepareFindNonEmptyChunks(CompressedMarchingCubeChunk chunk)
 {
     findNonEmptyAreasShader.SetInt("pointSpacing", chunk.PointSpacing);
     findNonEmptyAreasShader.SetInt("lod", chunk.LOD);
     findNonEmptyAreasShader.SetVector("anchorPosition", VectorExtension.ToVector4(chunk.AnchorPos));
     findNonEmptyAreasShader.SetInt("numPointsPerAxis", chunk.NoisePointsPerAxis);
     findNonEmptyAreasShader.SetBuffer(0, "points", pointsBuffer);
     chunkPositionBuffer.SetCounterValue(0);
 }
コード例 #13
0
        public void NudgeTowardsPosition(Vector2Int startPosition, Vector2Int endPosition)
        {
            var direction       = startPosition.GetVectorDirection(endPosition);
            var vectorDirection = VectorExtension.GetVectorTowardsDirection(direction);
            var partialVector   = new Vector3()
            {
                x = (float)(vectorDirection.x * 0.25),
                y = (float)(vectorDirection.y * 0.25),
                z = 0.0f
            };
            var movePosition = startPosition.ToVector3() + partialVector;

            var currentPosition = new Vector3(startPosition.x, startPosition.y);
            var path            = new List <Vector3>()
            {
                currentPosition,
            };

            const float INTERVAL = (float)0.10;

            while (Vector3.Distance(currentPosition, movePosition) > 0.005f)
            {
                var nextPosition = Vector3.MoveTowards(currentPosition, movePosition, INTERVAL);
                if (partialVector.x != 0)
                {
                    currentPosition.x = nextPosition.x;
                }
                if (partialVector.y != 0)
                {
                    currentPosition.y = nextPosition.y;
                }
                path.Add(nextPosition);
            }
            path.Remove(path.Last());
            path.Add(movePosition);

            while (Vector3.Distance(currentPosition, startPosition.ToVector3()) > 0.005f)
            {
                var nextPosition = Vector3.MoveTowards(currentPosition, startPosition.ToVector3(), INTERVAL);
                if (partialVector.x != 0)
                {
                    currentPosition.x = nextPosition.x;
                }
                if (partialVector.y != 0)
                {
                    currentPosition.y = nextPosition.y;
                }
                path.Add(nextPosition);
            }
            path.Remove(path.Last());
            path.Add(startPosition.ToVector3());

            var mover = GameObject.GetComponent <UnitMover>();

            mover.SetPath(path);
        }
コード例 #14
0
        public void ApplyDensityPropertiesForChunk(CompressedMarchingCubeChunk chunk, bool tryLoadData = true)
        {
            Vector4 anchor        = VectorExtension.ToVector4(chunk.AnchorPos);
            int     pointsPerAxis = chunk.PointsPerAxis;

            densityGeneratorShader.SetVector("anchor", anchor);
            densityGeneratorShader.SetInt("numPointsPerAxis", pointsPerAxis);
            densityGeneratorShader.SetFloat("spacing", chunk.LOD);
            densityGeneratorShader.SetBool("tryLoadData", tryLoadData);
        }
コード例 #15
0
        /// <summary>
        /// Wird aufgerufen, wenn eine Linien-Geste erkannt wurde
        /// </summary>
        /// <param name="element"></param>
        /// <param name="points"></param>
        private void LineCallback(UIElement element, ScrumGestures.TouchGroup points)
        {
            TouchPoint tp = points[0];

            //We need at least 2 points
            this.Surface.Dispatcher.Invoke(new Action(() =>
            {
                this.SortByPriority(tp.StartPoint, VectorExtension.FromPoints(tp.StartPoint, tp.CurrentPoint));
            }));
        }
コード例 #16
0
 protected void BuildAllChunksAsync(Vector3Int[] pos)
 {
     for (int i = 0; i < pos.Length; i++)
     {
         Vector3Int next = pos[i];
         if (!chunkGroup.HasChunkStartedAt(VectorExtension.ToArray(next)))
         {
             CreateChunkWithAsyncGPUReadback(next, FindNeighbourOfChunk);
         }
         ;
     }
 }
コード例 #17
0
        public void GetDirectCosTest_AssertMustBeEqual()
        {
            // Arrange
            Vector <double> va       = new double[] { 1, 2, 3 };
            Vector <double> expected = new[] { 0.2672612419124244, 0.5345224838248488, 0.8017837257372732 };

            // Act
            var actual = VectorExtension.GetDirectCos(va);

            // Assert
            Assert.Equal(expected, actual);
        }
コード例 #18
0
        public void GetDistancePointVectorTest_AssertMustBeEqual()
        {
            // Arrange
            Vector <int> v1       = new[] { 4, 2, 1, 1, 2, 3, 4, 6, 9 };
            Vector <int> v2       = new[] { 4, 2, 4, 1, 3, 4, 5, 7, 11 };
            Vector <int> expected = new[] { 0, 0, 3, 0, 1, 1, 1, 1, 2 };

            // Act
            var actual = VectorExtension.GetDistancePoint(v1, v2);

            // Assert
            Assert.Equal(expected, actual);
        }
コード例 #19
0
        public void GetDirectCosTest2_AssertMustBeEqual()
        {
            // Arrange
            Vector <double> va       = new double[] { 1, 2, 3 };
            Vector <double> vb       = new double[] { 4, 5, 6 };
            Vector <double> expected = new[] { 0.5773502691896257, 0.5773502691896257, 0.5773502691896257 };

            // Act
            var actual = VectorExtension.GetDirectCos(va, vb);

            // Assert
            Assert.Equal(expected, actual);
        }
コード例 #20
0
        protected void CheckIfNeighboursExistAlready()
        {
            Vector3Int v3;

            for (int i = 0; i < 6; i++)
            {
                if (hasNeighbourInDirection[i])
                {
                    v3 = VectorExtension.GetDirectionFromIndex(i) * (chunk.ChunkSize + 1) + chunk.CenterPos;
                    hasNeighbourInDirection[i] = !chunkGroup.HasChunkStartedAt(VectorExtension.ToArray(v3));
                }
            }
        }
コード例 #21
0
        private static Vector4 hueToRGB(float hue)
        {
            float h6 = hue * 6;

            Vector4 ret = new Vector4(
                Math.Abs(3 - h6) - 1,
                2 - Math.Abs(2 - h6),
                2 - Math.Abs(4 - h6),
                0);

            VectorExtension.Clamp0_1(ref ret);
            return(ret);
        }
コード例 #22
0
        protected void PrepareEnvironmentForChunk(IEnvironmentSurface chunk)
        {
            environmentEntities.SetCounterValue(0);
            environmentSpawner.SetBuffer(0, "minAngleAtCubeIndex", chunk.MinDegreeBuffer);
            Vector4 v4 = VectorExtension.ToVector4(chunk.AnchorPos);

            environmentSpawner.SetVector("anchorPosition", v4);
            environmentPlacer.SetVector("anchorPosition", v4);
            environmentPlacer.SetVector(BOUNDS_CENTER_NAME, chunk.MeshBounds.Value.center);
            if (chunk.BuildDetailedEnvironment)
            {
            }
        }
コード例 #23
0
        public void AddEnvirenmentForEditedChunk(CompressedMarchingCubeChunk chunk, bool buildDetailEnvironment)
        {
            environmentSpawner.SetBuffer(0, "minAngleAtCubeIndex", chunk.MinDegreeBuffer);
            environmentSpawner.SetVector("anchorPosition", VectorExtension.ToVector4(chunk.AnchorPos));
            environmentSpawner.Dispatch(0, THREADS_PER_AXIS, THREADS_PER_AXIS, THREADS_PER_AXIS);
            int[] results = ComputeBufferExtension.ReadAppendBuffer <int>(environmentEntities, bufferCount);

            //AsyncGPUReadback.Request(environmentEntities, OnTreePositionsRecieved);

            //recieve tree positions
            //recieve tree rotations -> place colliders from pool
            //add grass to unused cubes
            //when editing chunk store tree positions and rotations and original cubes
        }
コード例 #24
0
        protected virtual void ResizeCallback(UIElement element, TouchGroup points)
        {
            RemoveResizeAnimation();

            Vector vec1 = VectorExtension.FromPoints(points[0].CurrentPoint, points[1].CurrentPoint);
            Vector vec2 = VectorExtension.FromPoints(points[0].PreviousPoint, points[1].PreviousPoint);

            double distanceChange = vec1.Length - vec2.Length;

            double w = this.ScaledWidth + distanceChange;
            double h = this.ScaledHeight + distanceChange;

            //Neue Größe festlegen. Die aufgerufene Methode passt den Skalierungsfaktor der Größe an
            this.SetSize(w, h);
        }
コード例 #25
0
        public void SpawnEmptyChunksAround(IMarchingCubeChunk c)
        {
            bool[] dirs  = c.HasNeighbourInDirection;
            int    count = dirs.Length;

            for (int i = 0; i < count; i++)
            {
                if (!dirs[i])
                {
                    continue;
                }
                Vector3Int v3 = VectorExtension.GetDirectionFromIndex(i) * (c.ChunkSize + 1) + c.CenterPos;
                BuildEmptyChunkAt(v3);
            }
        }
コード例 #26
0
        public void TestProjection()
        {
            var a = new Vector2(0.5F, 1);

            a = VectorExtension.Projection(a, new Vector2(1, 1));
            Debug.Log($"({a.x},{a.y})");

            var b = new Vector2(0.5F, 1);

            b = VectorExtension.Reflection(b, new Vector2(1, -1));
            Debug.Log($"({b.x},{b.y})");

            var c = new float3(0, 0, 1);

            Debug.Log(VectorExtension.Projection(c, new float3(1, 1, 1)));
        }
コード例 #27
0
        protected virtual void RotateCallback(UIElement element, TouchGroup points)
        {
            RemoveRotateAnimation();

            Vector vec1 = VectorExtension.FromPoints(points[0].CurrentPoint, points[1].CurrentPoint);
            Vector vec2 = VectorExtension.FromPoints(points[0].PreviousPoint, points[1].PreviousPoint);

            double slopeChanged = vec2.GetAngle(vec1);

            if (!rotateInProgress && slopeChanged != 0)
            {
                //Neuen Winkel festlegen durch Addition
                this.RotateAngle += slopeChanged;
                rotateInProgress  = false;
            }
        }
コード例 #28
0
        /// <summary>
        /// returns true if the chunk was created
        /// </summary>
        /// <param name="p"></param>
        /// <param name="editPoint"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="delta"></param>
        /// <param name="maxDistance"></param>
        /// <param name="chunk"></param>
        /// <returns></returns>
        public void CreateChunkWithNoiseEdit(Vector3Int p, Vector3 editPoint, Vector3Int start, Vector3Int end, float delta, float maxDistance, out CompressedMarchingCubeChunk chunk)
        {
            bool hasChunkAtPosition = chunkGroup.TryGetGroupItemAt(VectorExtension.ToArray(p), out chunk);

            if (!hasChunkAtPosition || !chunk.HasStarted)
            {
                if (chunk != null)
                {
                    ///current chunk is marks border of generated chunks, so destroy it
                    chunk.DestroyChunk();
                }
                chunk = CreateChunkWithProperties(p, 0, DEFAULT_CHUNK_SIZE_POWER, false,
                                                  (b) => {
                    ApplyNoiseEditing(b, editPoint, start, end, delta, maxDistance);
                });
            }
        }
コード例 #29
0
        /// <summary>
        ///  Builds the Move request end hands it to the forwarder.
        /// </summary>
        internal static void DistractingShotRequest(Vector3 lookDir)
        {
            var data = new Dictionary <byte, object>
            {
                { (byte)ParameterCode.ActionCode, ActionCode.DistractingShot },
                { (byte)ParameterCode.LookDirection, VectorExtension.Vector3ToVector(lookDir) }
            };

            var operationRequest = new OperationRequest()
            {
                OperationCode = (byte)OperationCode.CharacterAction,
                Parameters    = data
            };

            RequestForwarder.ForwardRequest(
                operationRequest,
                true,
                0);
        }
コード例 #30
0
        public void TensorProductTest_AssertMustBeEqual()
        {
            // Arrange
            Vector <double> v1       = new double[] { 1, 2, 3, 4, 5 };
            Vector <double> v2       = new double[] { 6, 7, 8, 9, 10 };
            Matrix <double> expected = new double[, ]
            {
                { 6, 7, 8, 9, 10 },
                { 12, 14, 16, 18, 20 },
                { 18, 21, 24, 27, 30 },
                { 24, 28, 32, 36, 40 },
                { 30, 35, 40, 45, 50 }
            };

            // Act
            var actual = VectorExtension.TensorProduct(v1, v2);

            // Assert
            Assert.Equal(expected, actual);
        }