Esempio n. 1
0
 public static void Main()
 {
     DynamicArray<string> arrey = new DynamicArray<string>();
     arrey.Add("Pesho");
     arrey.Add("Gosho");
     Console.WriteLine(arrey.IndexOf("Pesho"));
     Console.WriteLine(arrey.Contains("Gosho"));
     Console.WriteLine(arrey.Contains("Ivan"));
     arrey.Remove("Pesho");
     arrey.InsertAt(1, "Pesho");
     arrey.Clear();
     Console.WriteLine(arrey.Capacity);
     Console.WriteLine(arrey.Count);
     arrey.Add("Ivo");
     arrey[0] = "Gosho";
     var newArrey = arrey.ToArray();
     Console.WriteLine();
     foreach (var item in arrey)
     {
         Console.WriteLine(item);
     }
     Console.WriteLine();
     foreach (var item in newArrey)
     {
         Console.WriteLine(item);
     }
 }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var array = new DynamicArray<string>();
            array.Add("Georgi");
            array.Add("Nikolai");
            Console.WriteLine(array.IndexOf("Nikolai"));
            Console.WriteLine(array.Cointains("Kiril"));
            array.Remove("Georgi");
            array.InsertAt(1, "Ivan");
            array.Clear();
            Console.WriteLine(array.Capacity);
            Console.WriteLine(array.Count);

            array.Add("Stefan");
            array.Add("Krum");
            var arr = array.ToArray();
            Console.WriteLine();
            foreach (var item in array)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();

            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
        }
 public void AddMoreThanCapacityTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>(2);
     Arr.Add(65);
     Arr.Add(16);
     Arr.Add(76);
     Assert.AreEqual(Arr.Length, 3);
     Assert.AreEqual(Arr.Capacity, 4);
     Assert.AreEqual(Arr[2], 76);
 }
Esempio n. 4
0
 public void AddTest()
 {
     DynamicArray<int> testArr = new DynamicArray<int>(4);
     testArr.Add(0);
     testArr.Add(1);
     testArr.Add(2);
     testArr.Add(3);
     Assert.AreEqual(testArr[0], 0);
     Assert.AreEqual(testArr[1], 1);
     Assert.AreEqual(testArr[2], 2);
     Assert.AreEqual(testArr[3], 3);
 }
 public void AddRangeMoreThanCapacity()
 {
     int[] a = { 28, 98, 89, 25, 43 };
     DynamicArray<int> Arr = new DynamicArray<int>(2);
     Arr.Add(68);
     Arr.Add(73);
     Arr.AddRange(a);
     Assert.AreEqual(Arr.Length, 7);
     Assert.AreEqual(Arr.Capacity, 8);
     Assert.AreEqual(Arr[2], 28);
     Assert.AreEqual(Arr[6], 43);
 }
 public void AddTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>();
     Arr.Add(23);
     Assert.AreEqual(Arr.Length, 1);
     Assert.AreEqual(Arr[0], 23);
 }
Esempio n. 7
0
 public void RandomOperation()
 {
     var r = new Random();
     const int totalOperations = 10000;
     var target = new DynamicArray<int>();
     for (var i = 0; i < totalOperations; i++)
     {
         int oldCount = target.Count;
         switch (r.Next(3))
         {
             case 0: // Add
                 var newItem = r.Next();
                 target.Add(newItem);
                 Assert.AreEqual(oldCount + 1, target.Count);
                 Assert.AreEqual(newItem, target[oldCount]);
                 break;
             case  1: // Remove by index
                 if(oldCount == 0) goto case 0;
                 var indexToRemove = r.Next(oldCount - 1);
                 target.RemoveAt(indexToRemove);
                 Assert.AreEqual(oldCount - 1, target.Count);
                 break;
             case 2: // Remove by element
                 if (oldCount == 0) goto case 0;
                 var itemToRemove = target[r.Next(oldCount - 1)];
                 target.Remove(itemToRemove);
                 Assert.AreEqual(oldCount - 1, target.Count);
                 break;
         }
     }
 }
Esempio n. 8
0
   static void Main(string[] args)
   {
       DynamicArray<string> test = new DynamicArray<string>();
     //  test.Add("a");
    //   test.Add("b");
     //  test.Add("b");
       test.Add("c");
       test.Add("a");
   //    test.Add("b");
   //    test.Add("b");
       test.Add("c");
    //   test.Remove("b");
    //   test.Remove("b");
   //    test.Remove("b");
       test.Remove("b");
       test.Remove("a");
 
       Console.WriteLine(test[1]);
       test[1] = "f**k you";
       Console.WriteLine(test[1]);
   }
Esempio n. 9
0
        public void TestMethod1()
        {
            try
            {
                DynamicArray<int> m1 = new DynamicArray<int>();
                DynamicArray<int> m2 = new DynamicArray<int>(9);

                int[] arr = new[] { 1, 2, 3, 4, 5 };
                DynamicArray<int> m3 = new DynamicArray<int>(arr);

                var a = m3.Length;
                Assert.AreEqual(a, 5);
                var b = m3.Capacity;
                Assert.AreEqual(b, 5);

                m3.Add(6);
                var a1 = m3.Length;
                Assert.AreEqual(a1, 6);
                var b1 = m3.Capacity;
                Assert.AreEqual(b1, 10);

                int[] arr1 = new[] { 7, 8, 9, 10, 11, 12 };
                m3.AddRange(arr1);
                var a3 = m3.Length;
                Assert.AreEqual(a3, 12);
                var b3 = m3.Capacity;
                Assert.AreEqual(b3, 20);

                var flag1 = m3.Remove(7);
                var a4 = m3.Length;
                Assert.AreEqual(a4, 11);
                Assert.AreEqual(flag1, true);

                //m3.Insert(26,14); //Попытка вставить вне границ массива
                m3.Insert(6, 7);
                var b4 = m3[6];
                Assert.AreEqual(b4, 7);

                int k = 1;
                foreach (var elem in m3)
                {
                    var a5 = elem;
                    Assert.AreEqual(a5, k);
                    k++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Assert.AreEqual(0, 1);

            }
        }
Esempio n. 10
0
 public void TestInsertMethod()
 {
     DynamicArray<int> m3 = new DynamicArray<int>(9);
     int[] arr = new[] { 1, 2, 3, 4, 5 };
     foreach (var elem in arr)
     {
         m3.Add(elem);
     }
     m3.Insert(2, 9);
     var a1 = m3[2];
     Assert.AreEqual(a1, 9);
 }
Esempio n. 11
0
        public void TestAddMethod()
        {
            DynamicArray<int> m2 = new DynamicArray<int>(9);

            m2.Add(10);
            var a2 = m2.Length;
            Assert.AreEqual(a2, 1);
            var b2 = m2.Capacity;
            Assert.AreEqual(b2, 9);

            var a3 = m2[0];
            Assert.AreEqual(a3, 10);
        }
Esempio n. 12
0
        public void TestMethod1()
        {
            try
            {
                DynamicArray<int> arr1 = new DynamicArray<int>();
                DynamicArray<int> arr2 = new DynamicArray<int>(20);

                int[] arr3 = new[] { 1, 2, 3, 4, 5 };
                DynamicArray<int> arr4 = new DynamicArray<int>(arr3);

                var a = arr4.Length;
                Assert.AreEqual(a, 5);
                var b = arr4.Capacity;
                Assert.AreEqual(b, 5);

                arr4.Add(6);
                var a1 = arr4.Length;
                Assert.AreEqual(a1, 6);
                var b1 = arr4.Capacity;
                Assert.AreEqual(b1, 10);

                int[] arr31 = new[] { 7, 8, 9, 10, 11, 12 };
                arr4.AddRange(arr31);
                var a3 = arr4.Length;
                Assert.AreEqual(a3, 12);
                var b3 = arr4.Capacity;
                Assert.AreEqual(b3, 20);

                var flag1 = arr4.Remove(7);
                var a4 = arr4.Length;
                Assert.AreEqual(a4, 11);
                Assert.AreEqual(flag1, true);

                arr4.Insert(6, 7);
                var b4 = arr4[6];
                Assert.AreEqual(b4, 7);

                int k = 1;
                foreach (var elem in arr4)
                {
                    var a5 = elem;
                    Assert.AreEqual(a5, k);
                    k++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Assert.AreEqual(0, 1);
            }
        }
        public void TestAddMethodWithIncrease()
        {
            int[] arr = new[] { 1, 2, 3, 4, 5 };
            DynamicArray<int> m3 = new DynamicArray<int>(arr);

            m3.Add(10);
            var a = m3.Length;
            Assert.AreEqual(a, 6);
            var b = m3.Capacity;
            Assert.AreEqual(b, 10);

            var a3 = m3[5];
            Assert.AreEqual(a3, 10);
        }
Esempio n. 14
0
        public void AddElements()
        {
            const int totalElements = 10000;
            var target = new DynamicArray<int>();
            foreach (var i in Enumerable.Range(1, totalElements))
            {
                target.Add(i);
            }
            Assert.AreEqual(totalElements, target.Count);

            for (var i = 0; i < totalElements; i++)
            {
                Assert.AreEqual(i+1, target[i]);
            }
        }
        /// <summary>
        /// Gets the walkable successors of the specified node.
        /// </summary>
        /// <param name="current">The current node.</param>
        /// <param name="successorArray">The array to fill with successors.</param>
        /// <returns>
        /// All walkable successors of the node.
        /// </returns>
        protected override void GetWalkableSuccessors(IPathNode current, DynamicArray<IPathNode> successorArray)
        {
            _neighbours.Clear();

            if (current.predecessor == null)
            {
                current.GetWalkableNeighbours(_neighbours, _unitProps, _cutCorners, false);
            }
            else if (current is IPortalNode)
            {
                current.GetWalkableNeighbours(successorArray, _unitProps, _cutCorners, false);
                return;
            }
            else
            {
                var dirFromPredecessor = current.predecessor.GetDirectionTo(current);
                PruneNeighbours(current, dirFromPredecessor);
            }

            var neighbourCount = _neighbours.count;
            for (int i = 0; i < neighbourCount; i++)
            {
                var n = _neighbours[i];
                if (n == null)
                {
                    break;
                }

                var dirToNeighbour = current.GetDirectionTo(n);
                var jp = Jump(current, dirToNeighbour);
                if (jp != null)
                {
                    successorArray.Add(jp);
                }
            }
        }
Esempio n. 16
0
        public override void Load(ValuesDictionary valuesDictionary)
        {
            base.Load(valuesDictionary);
            Utils.Load(Project);
            //Utils.SubsystemItemsScanner.ItemsScanned += GarbageCollectItems;
            var arr = valuesDictionary.GetValue("AlloysData", "0").Split(',');

            AlloysData = new DynamicArray <Metal>(arr.Length);
            int i;

            for (i = 0; i < arr.Length; i++)
            {
                if (short.TryParse(arr[i], NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out short value))
                {
                    AlloysData.Add((Metal)value);
                }
            }
            SmallBrushes = new TerrainBrush[16];
            PtBrushes    = new TerrainBrush[16];
            BBrushes     = new TerrainBrush[16];
            ABrushes     = new TerrainBrush[16];
            //NaruralGasBrushes = new TerrainBrush[16];
            OilPocketCells = new TerrainBrush.Cell[16][];
            //MinCounts = new int[12, 16];
            var          random = new Random(17034);
            TerrainBrush brush;
            int          j, k;

            for (i = 0; i < 16; i++)
            {
                brush = new TerrainBrush();
                Vector3 v, vec;
                for (j = random.Int() & 1; j-- != 0;)
                {
                    v   = 0.5f * Vector3.Normalize(new Vector3(random.UniformFloat(-1f, 1f), random.UniformFloat(-1f, 1f), random.UniformFloat(-1f, 1f)));
                    vec = Vector3.Zero;
                    for (k = random.UniformInt(2, 5); k-- != 0;)
                    {
                        brush.AddBox((int)MathUtils.Floor(vec.X), (int)MathUtils.Floor(vec.Y), (int)MathUtils.Floor(vec.Z), 1, 1, 1, 1);                         //Ag
                        vec += v;
                    }
                }
                brush.Compile();
                SmallBrushes[i] = brush;
                brush           = new TerrainBrush();
                for (j = random.UniformInt(1, 3); j-- != 0;)
                {
                    v   = 0.5f * Vector3.Normalize(new Vector3(random.UniformFloat(-1f, 1f), random.UniformFloat(-2f, 2f), random.UniformFloat(-1f, 1f)));
                    vec = Vector3.Zero;
                    for (k = random.UniformInt(2, 3); k-- != 0;)
                    {
                        brush.AddBox((int)MathUtils.Floor(vec.X), (int)MathUtils.Floor(vec.Y), (int)MathUtils.Floor(vec.Z), 1, 1, 1, 2);                         //Pt
                        vec += v;
                    }
                }
                brush.Compile();
                PtBrushes[i] = brush;
                brush        = new TerrainBrush();
                for (j = random.UniformInt(2, 4); j-- != 0;)
                {
                    v   = 0.5f * Vector3.Normalize(new Vector3(random.UniformFloat(-1f, 1f), random.UniformFloat(-0.25f, 0.25f), random.UniformFloat(-1f, 1f)));
                    vec = Vector3.Zero;
                    for (k = random.UniformInt(3, 5); k-- != 0;)
                    {
                        brush.AddBox((int)MathUtils.Floor(vec.X), (int)MathUtils.Floor(vec.Y), (int)MathUtils.Floor(vec.Z), 1, 1, 1, 8);                         //Ti
                        vec += v;
                    }
                }
                brush.Compile();
                ABrushes[i] = brush;
                brush       = new TerrainBrush();
                for (j = random.UniformInt(3, 5); j-- != 0;)
                {
                    v   = 0.5f * Vector3.Normalize(new Vector3(random.UniformFloat(-1f, 1f), random.UniformFloat(-1f, 1f), random.UniformFloat(-1f, 1f)));
                    vec = Vector3.Zero;
                    for (k = random.UniformInt(2, 5); k-- != 0;)
                    {
                        brush.AddBox((int)MathUtils.Floor(vec.X), (int)MathUtils.Floor(vec.Y), (int)MathUtils.Floor(vec.Z), 1, 1, 1, 5);                         //Sn
                        vec += v;
                    }
                }
                brush.Compile();
                BBrushes[i] = brush;
                var cells = TerrainContentsGenerator.m_basaltPocketBrushes[i].Cells;
                OilPocketCells[i] = new TerrainBrush.Cell[j = cells.Length];
                while (j-- != 0)
                {
                    if ((cells[j].Value & random.Int()) != 0)
                    {
                        OilPocketCells[i][j]       = cells[j];
                        OilPocketCells[i][j].Value = RottenMeatBlock.Index | 1 << 4 << 14;
                    }
                }
            }
        }
Esempio n. 17
0
 void IPathNode.GetWalkableNeighbours(DynamicArray<IPathNode> neighbours, AttributeMask requesterAttributes, bool cornerCuttingAllowed, bool preventDiagonalMoves)
 {
     var destinationNodes = _partner._neighbourNodes;
     var nodeCount = destinationNodes.Length;
     for (int i = 0; i < nodeCount; i++)
     {
         if (destinationNodes[i].isWalkable(requesterAttributes))
         {
             neighbours.Add(destinationNodes[i]);
         }
     }
 }
Esempio n. 18
0
    static void Main()
    {
        const int  REPEATS = 50;
        const int  SIZE    = 1000000;
        List <int> list    = new List <int>(SIZE);
        Random     rand    = new Random(12345);

        for (int i = 0; i < SIZE; i++)
        {
            list.Add(rand.Next(5000));
        }
        int[] arr = list.ToArray();
        DynamicArray <int> darr = new DynamicArray <int>();

        foreach (int v in list)
        {
            darr.Add(v);
        }

        long      hits  = 0;
        long      chk   = 0;
        Stopwatch watch = Stopwatch.StartNew();

        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                chk += list[i];
                hits++;
            }
        }
        watch.Stop();
        Console.WriteLine("List/for      : {0}ms ({1})  ", watch.ElapsedMilliseconds, chk);

        chk   = 0;
        hits  = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                chk += arr[i];
                hits++;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/for     : {0}ms ({1})", watch.ElapsedMilliseconds, chk);


        chk   = 0;
        hits  = 0;
        watch = Stopwatch.StartNew();
        int[] arr2 = darr.Compact();
        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            for (int i = 0; i < arr2.Length; i++)
            {
                chk += arr2[i];
                hits++;
            }
        }
        watch.Stop();
        Console.WriteLine("DArray/for    : {0}ms ({1})", watch.ElapsedMilliseconds, chk);



        Console.WriteLine();
        chk   = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            foreach (int i in list)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("List/foreach  : {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk   = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            foreach (int i in arr)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/foreach : {0}ms ({1})", watch.ElapsedMilliseconds, chk);


        chk   = 0;
        watch = Stopwatch.StartNew();
        int[] c = darr.Compact();
        for (int rpt = 0; rpt < REPEATS; rpt++)
        {
            foreach (int i in c)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("DArray/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
        Console.WriteLine();
        Console.WriteLine("Total number of hits: {0:N0}", hits);
        Console.ReadKey();
    }
        /// <summary>
        /// Updates the cell streaming for a <see cref="Camera"/>
        /// </summary>
        /// <param name="camera">The <see cref="Camera"/></param>
        public void UpdateCellStreaming(Camera camera)
        {
            if (!isInitialized)
            {
                return;
            }

            var cameraPosition = camera.transform.position;

            if (!debugDisplay.freezeStreaming)
            {
                m_FrozenCameraPosition = cameraPosition;
            }

            // Cell position in cell space is the top left corner. So we need to shift the camera position by half a cell to make things comparable.
            var cameraPositionCellSpace = (m_FrozenCameraPosition - m_Transform.posWS) / MaxBrickSize() - Vector3.one * 0.5f;

            ComputeCellCameraDistance(cameraPositionCellSpace, m_ToBeLoadedCells);
            ComputeCellCameraDistance(cameraPositionCellSpace, m_LoadedCells);

            m_ToBeLoadedCells.QuickSort();
            m_LoadedCells.QuickSort();

            // This is only a rough budget estimate at first.
            // It doesn't account for fragmentation.
            int indexChunkBudget = m_Index.GetRemainingChunkCount();
            int shChunkBudget    = m_Pool.GetRemainingChunkCount();

            if (m_SupportStreaming)
            {
                bool budgetReached = false;

                while (m_TempCellToLoadList.size < m_NumberOfCellsLoadedPerFrame && m_TempCellToLoadList.size < m_ToBeLoadedCells.size && !budgetReached)
                {
                    // Enough memory, we can safely load the cell.
                    var cellInfo = m_ToBeLoadedCells[m_TempCellToLoadList.size];
                    budgetReached = !TryLoadCell(cellInfo, ref shChunkBudget, ref indexChunkBudget, m_TempCellToLoadList);
                }

                // Budget reached. We need to figure out if we can safely unload other cells to make room.
                if (budgetReached)
                {
                    int  pendingUnloadCount = 0;
                    bool canUnloadCell      = true;
                    while (canUnloadCell && m_TempCellToLoadList.size < m_NumberOfCellsLoadedPerFrame && m_TempCellToLoadList.size < m_ToBeLoadedCells.size)
                    {
                        if (m_LoadedCells.size - pendingUnloadCount == 0)
                        {
                            canUnloadCell = false;
                            break;
                        }

                        var furthestLoadedCell  = m_LoadedCells[m_LoadedCells.size - pendingUnloadCount - 1];
                        var closestUnloadedCell = m_ToBeLoadedCells[m_TempCellToLoadList.size];

                        // Redundant work. Maybe store during first sort pass?
                        float furthestLoadedCellDistance  = Vector3.Distance(furthestLoadedCell.cell.position, cameraPositionCellSpace);
                        float closestUnloadedCellDistance = Vector3.Distance(closestUnloadedCell.cell.position, cameraPositionCellSpace);

                        // The most distant loaded cell is further than the closest unloaded cell, we can unload it.
                        if (furthestLoadedCellDistance > closestUnloadedCellDistance)
                        {
                            pendingUnloadCount++;
                            UnloadCell(furthestLoadedCell);
                            shChunkBudget    += furthestLoadedCell.cell.shChunkCount;
                            indexChunkBudget += furthestLoadedCell.cell.indexChunkCount;

                            m_TempCellToUnloadList.Add(furthestLoadedCell);

                            TryLoadCell(closestUnloadedCell, ref shChunkBudget, ref indexChunkBudget, m_TempCellToLoadList);
                        }
                        else
                        {
                            // We are in a "stable" state, all the closest cells are loaded within the budget.
                            canUnloadCell = false;
                        }
                    }

                    if (pendingUnloadCount > 0)
                    {
                        m_LoadedCells.RemoveRange(m_LoadedCells.size - pendingUnloadCount, pendingUnloadCount);
                        RecomputeMinMaxLoadedCellPos();
                    }
                }
            }
            else
            {
                int cellCountToLoad = Mathf.Min(m_NumberOfCellsLoadedPerFrame, m_ToBeLoadedCells.size);
                for (int i = 0; i < cellCountToLoad; ++i)
                {
                    var cellInfo = m_ToBeLoadedCells[m_TempCellToLoadList.size]; // m_TempCellToLoadList.size get incremented in TryLoadCell
                    TryLoadCell(cellInfo, ref shChunkBudget, ref indexChunkBudget, m_TempCellToLoadList);
                }
            }

            // Remove the cells we successfully loaded.
            m_ToBeLoadedCells.RemoveRange(0, m_TempCellToLoadList.size);
            m_LoadedCells.AddRange(m_TempCellToLoadList);
            m_ToBeLoadedCells.AddRange(m_TempCellToUnloadList);
            m_TempCellToLoadList.Clear();
            m_TempCellToUnloadList.Clear();
        }
Esempio n. 20
0
        public void AppendModelMeshPart(ModelMeshPart meshPart, Matrix matrix, bool makeEmissive, bool flipWindingOrder, bool doubleSided, bool flipNormals, Color color)
        {
            VertexBuffer vertexBuffer = meshPart.VertexBuffer;
            IndexBuffer  indexBuffer  = meshPart.IndexBuffer;
            ReadOnlyList <VertexElement> vertexElements = vertexBuffer.VertexDeclaration.VertexElements;

            if (vertexElements.Count != 3 || vertexElements[0].Offset != 0 || vertexElements[0].Semantic != VertexElementSemantic.Position.GetSemanticString() || vertexElements[1].Offset != 12 || vertexElements[1].Semantic != VertexElementSemantic.Normal.GetSemanticString() || vertexElements[2].Offset != 24 || vertexElements[2].Semantic != VertexElementSemantic.TextureCoordinate.GetSemanticString())
            {
                throw new InvalidOperationException("Wrong vertex format for a block mesh.");
            }
            publicVertex[] vertexData = GetVertexData <publicVertex>(vertexBuffer);
            ushort[]       indexData  = GetIndexData <ushort>(indexBuffer);
            Dictionary <ushort, ushort> dictionary = new Dictionary <ushort, ushort>();

            for (int i = meshPart.StartIndex; i < meshPart.StartIndex + meshPart.IndicesCount; i++)
            {
                ushort num = indexData[i];
                if (!dictionary.ContainsKey(num))
                {
                    dictionary.Add(num, (ushort)Vertices.Count);
                    BlockMeshVertex item = default(BlockMeshVertex);
                    item.Position           = Vector3.Transform(vertexData[num].Position, matrix);
                    item.TextureCoordinates = vertexData[num].TextureCoordinate;
                    Vector3 vector = Vector3.Normalize(Vector3.TransformNormal(flipNormals ? (-vertexData[num].Normal) : vertexData[num].Normal, matrix));
                    if (makeEmissive)
                    {
                        item.IsEmissive = true;
                        item.Color      = color;
                    }
                    else
                    {
                        item.Color   = color * LightingManager.CalculateLighting(vector);
                        item.Color.A = color.A;
                    }
                    item.Face = (byte)CellFace.Vector3ToFace(vector);
                    Vertices.Add(item);
                }
            }
            for (int j = 0; j < meshPart.IndicesCount / 3; j++)
            {
                if (doubleSided)
                {
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 1]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 2]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 2]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 1]]);
                }
                else if (flipWindingOrder)
                {
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 2]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 1]]);
                }
                else
                {
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 1]]);
                    Indices.Add(dictionary[indexData[meshPart.StartIndex + 3 * j + 2]]);
                }
            }
            Trim();
        }
Esempio n. 21
0
        void IPathNode.GetVirtualNeighbours(DynamicArray<IPathNode> neighbours, AttributeMask requesterAttributes)
        {
            if (_virtualNeighbours == null)
            {
                return;
            }

            for (int i = 0; i < _virtualNeighbours.Count; i++)
            {
                var vn = _virtualNeighbours[i];
                if (vn.isWalkable(requesterAttributes))
                {
                    neighbours.Add(vn);
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Executes the update.
        /// </summary>
        /// <param name="deltaTime">The delta time, i.e. the time passed since the last update.</param>
        /// <param name="nextInterval">The time that will pass until the next update.</param>
        /// <returns>
        /// Can return the next interval by which the update should run. To use the default interval return null.
        /// </returns>
        float?ILoadBalanced.ExecuteUpdate(float deltaTime, float nextInterval)
        {
            _units.Clear();

            Vector3 currentPos = _unitData.position;
            // only project the position if forecastDistance is not 0
            Vector3 projPos = this.forecastDistance != 0f ? currentPos + (_unitData.velocity.normalized * this.forecastDistance) : currentPos;

            // get all colliders with 'blocks' layer
            _blocks = UnityServices.physics.OverlapSphere(projPos, this.scanRadius, Layers.blocks);

            // get all colliders with 'units' layer
            var units      = UnityServices.physics.OverlapSphere(projPos, this.scanRadius, Layers.units);
            int unitsCount = units.Length;

            if (unitsCount == 0)
            {
                // if there are no scanned units, then just return early
                return(null);
            }

            float unitBaseY = _unitData.basePosition.y;

            var unitManager = GameServices.gameStateManager;

            for (int i = 0; i < unitsCount; i++)
            {
                Collider other = units[i];
                if (other == null || other.Equals(_unitData.collider))
                {
                    // make sure to null out units with a missing collider OR units that match itself (this unit)
                    continue;
                }

                var   otherData  = unitManager.GetUnitFacade(other.gameObject, true);
                float otherBaseY = otherData.basePosition.y;
                if (unitBaseY + _unitData.height < otherBaseY || unitBaseY > otherBaseY + otherData.height)
                {
                    // ignore if the other unit is at a different elevation
                    continue;
                }

                if (this.filterAwayUnitsInSameGroup)
                {
                    var otherGroup = otherData.transientGroup;
                    if (otherGroup != null && object.ReferenceEquals(otherGroup, _unitData.transientGroup))
                    {
                        // filter away units that are in the same transient unit group as this unit (optionally)
                        continue;
                    }
                }

                // if we get to here, add the scanned unit's UnitFacade to the list
                _units.Add(otherData);
            }

            if (this.sortUnitsWithDistance)
            {
                // sort identified units depending on their distance to this unit (nearest first)
                _unitComparer.compareTo = currentPos;
                _units.Sort(_unitComparer);
            }

            return(null);
        }
Esempio n. 23
0
 public virtual void Add(TransientGroup <T> group)
 {
     _members.Add(group);
 }
Esempio n. 24
0
 /// <summary>
 /// Registers the portal component with this manager.
 /// </summary>
 /// <param name="portal">The portal component.</param>
 public void RegisterPortalComponent(GridPortalComponent portal)
 {
     _portalComponents.Add(portal);
 }
Esempio n. 25
0
        public void TestContainElement()
        {
            m_DynamicArray.Add(2);

            Assert.IsTrue(m_DynamicArray.Contains(2));
            Assert.IsFalse(m_DynamicArray.Contains(55));
        }
Esempio n. 26
0
        public override void GenerateTerrainVertices(BlockGeometryGenerator generator, TerrainGeometry geometry, int value, int x, int y, int z)
        {
            TerrainGeometrySubset[] alphaTestSubsetsByFace = geometry.AlphaTestSubsetsByFace;
            int data   = Terrain.ExtractData(value);
            int value2 = (y + 1 < 256) ? generator.Terrain.GetCellValueFast(x, y + 1, z) : 0;
            int num    = Terrain.ExtractContents(value2);
            int data2  = Terrain.ExtractData(value2);
            int value3 = (y + 2 < 256) ? generator.Terrain.GetCellValueFast(x, y + 2, z) : 0;
            int num2   = Terrain.ExtractContents(value3);
            int data3  = Terrain.ExtractData(value3);

            if (HasFireOnFace(data, 0))
            {
                int value4 = (y + 1 < 256) ? generator.Terrain.GetCellValueFast(x, y + 1, z + 1) : 0;
                int num3   = Terrain.ExtractContents(value4);
                int data4  = Terrain.ExtractData(value4);
                int value5 = (y + 2 < 256) ? generator.Terrain.GetCellValueFast(x, y + 2, z + 1) : 0;
                int num4   = Terrain.ExtractContents(value5);
                int data5  = Terrain.ExtractData(value5);
                int num5   = DefaultTextureSlot;
                if ((num == 104 && HasFireOnFace(data2, 0)) || (num3 == 104 && HasFireOnFace(data4, 2)))
                {
                    num5 += 16;
                    if ((num2 == 104 && HasFireOnFace(data3, 0)) || (num4 == 104 && HasFireOnFace(data5, 2)))
                    {
                        num5 += 16;
                    }
                }
                DynamicArray <TerrainVertex> vertices = alphaTestSubsetsByFace[0].Vertices;
                DynamicArray <ushort>        indices  = alphaTestSubsetsByFace[0].Indices;
                int count = vertices.Count;
                vertices.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z + 1, Color.White, num5, 0, ref vertices.Array[count]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z + 1, Color.White, num5, 1, ref vertices.Array[count + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z + 1, Color.White, num5, 2, ref vertices.Array[count + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z + 1, Color.White, num5, 3, ref vertices.Array[count + 3]);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)count);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)(count + 2));
            }
            if (HasFireOnFace(data, 1))
            {
                int value6 = (y + 1 < 256) ? generator.Terrain.GetCellValueFast(x + 1, y + 1, z) : 0;
                int num6   = Terrain.ExtractContents(value6);
                int data6  = Terrain.ExtractData(value6);
                int value7 = (y + 2 < 256) ? generator.Terrain.GetCellValueFast(x + 1, y + 2, z) : 0;
                int num7   = Terrain.ExtractContents(value7);
                int data7  = Terrain.ExtractData(value7);
                int num8   = DefaultTextureSlot;
                if ((num == 104 && HasFireOnFace(data2, 1)) || (num6 == 104 && HasFireOnFace(data6, 3)))
                {
                    num8 += 16;
                    if ((num2 == 104 && HasFireOnFace(data3, 1)) || (num7 == 104 && HasFireOnFace(data7, 3)))
                    {
                        num8 += 16;
                    }
                }
                DynamicArray <TerrainVertex> vertices2 = alphaTestSubsetsByFace[1].Vertices;
                DynamicArray <ushort>        indices2  = alphaTestSubsetsByFace[1].Indices;
                int count2 = vertices2.Count;
                vertices2.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z, Color.White, num8, 0, ref vertices2.Array[count2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z, Color.White, num8, 3, ref vertices2.Array[count2 + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z + 1, Color.White, num8, 2, ref vertices2.Array[count2 + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z + 1, Color.White, num8, 1, ref vertices2.Array[count2 + 3]);
                indices2.Add((ushort)count2);
                indices2.Add((ushort)(count2 + 1));
                indices2.Add((ushort)(count2 + 2));
                indices2.Add((ushort)(count2 + 2));
                indices2.Add((ushort)(count2 + 1));
                indices2.Add((ushort)count2);
                indices2.Add((ushort)(count2 + 2));
                indices2.Add((ushort)(count2 + 3));
                indices2.Add((ushort)count2);
                indices2.Add((ushort)count2);
                indices2.Add((ushort)(count2 + 3));
                indices2.Add((ushort)(count2 + 2));
            }
            if (HasFireOnFace(data, 2))
            {
                int value8 = (y + 1 < 256) ? generator.Terrain.GetCellValueFast(x, y + 1, z - 1) : 0;
                int num9   = Terrain.ExtractContents(value8);
                int data8  = Terrain.ExtractData(value8);
                int value9 = (y + 2 < 256) ? generator.Terrain.GetCellValueFast(x, y + 2, z - 1) : 0;
                int num10  = Terrain.ExtractContents(value9);
                int data9  = Terrain.ExtractData(value9);
                int num11  = DefaultTextureSlot;
                if ((num == 104 && HasFireOnFace(data2, 2)) || (num9 == 104 && HasFireOnFace(data8, 0)))
                {
                    num11 += 16;
                    if ((num2 == 104 && HasFireOnFace(data3, 2)) || (num10 == 104 && HasFireOnFace(data9, 0)))
                    {
                        num11 += 16;
                    }
                }
                DynamicArray <TerrainVertex> vertices3 = alphaTestSubsetsByFace[2].Vertices;
                DynamicArray <ushort>        indices3  = alphaTestSubsetsByFace[2].Indices;
                int count3 = vertices3.Count;
                vertices3.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z, Color.White, num11, 0, ref vertices3.Array[count3]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z, Color.White, num11, 1, ref vertices3.Array[count3 + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z, Color.White, num11, 2, ref vertices3.Array[count3 + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z, Color.White, num11, 3, ref vertices3.Array[count3 + 3]);
                indices3.Add((ushort)count3);
                indices3.Add((ushort)(count3 + 2));
                indices3.Add((ushort)(count3 + 1));
                indices3.Add((ushort)(count3 + 1));
                indices3.Add((ushort)(count3 + 2));
                indices3.Add((ushort)count3);
                indices3.Add((ushort)(count3 + 2));
                indices3.Add((ushort)count3);
                indices3.Add((ushort)(count3 + 3));
                indices3.Add((ushort)(count3 + 3));
                indices3.Add((ushort)count3);
                indices3.Add((ushort)(count3 + 2));
            }
            if (!HasFireOnFace(data, 3))
            {
                return;
            }
            int value10 = (y + 1 < 256) ? generator.Terrain.GetCellValueFast(x - 1, y + 1, z) : 0;
            int num12   = Terrain.ExtractContents(value10);
            int data10  = Terrain.ExtractData(value10);
            int value11 = (y + 2 < 256) ? generator.Terrain.GetCellValueFast(x - 1, y + 2, z) : 0;
            int num13   = Terrain.ExtractContents(value11);
            int data11  = Terrain.ExtractData(value11);
            int num14   = DefaultTextureSlot;

            if ((num == 104 && HasFireOnFace(data2, 3)) || (num12 == 104 && HasFireOnFace(data10, 1)))
            {
                num14 += 16;
                if ((num2 == 104 && HasFireOnFace(data3, 3)) || (num13 == 104 && HasFireOnFace(data11, 1)))
                {
                    num14 += 16;
                }
            }
            DynamicArray <TerrainVertex> vertices4 = alphaTestSubsetsByFace[3].Vertices;
            DynamicArray <ushort>        indices4  = alphaTestSubsetsByFace[3].Indices;
            int count4 = vertices4.Count;

            vertices4.Count += 4;
            BlockGeometryGenerator.SetupLitCornerVertex(x, y, z, Color.White, num14, 0, ref vertices4.Array[count4]);
            BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z, Color.White, num14, 3, ref vertices4.Array[count4 + 1]);
            BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z + 1, Color.White, num14, 2, ref vertices4.Array[count4 + 2]);
            BlockGeometryGenerator.SetupLitCornerVertex(x, y, z + 1, Color.White, num14, 1, ref vertices4.Array[count4 + 3]);
            indices4.Add((ushort)count4);
            indices4.Add((ushort)(count4 + 2));
            indices4.Add((ushort)(count4 + 1));
            indices4.Add((ushort)(count4 + 1));
            indices4.Add((ushort)(count4 + 2));
            indices4.Add((ushort)count4);
            indices4.Add((ushort)(count4 + 2));
            indices4.Add((ushort)count4);
            indices4.Add((ushort)(count4 + 3));
            indices4.Add((ushort)(count4 + 3));
            indices4.Add((ushort)count4);
            indices4.Add((ushort)(count4 + 2));
        }
Esempio n. 27
0
        public void Size_WhenCalled_ShouldReturnNumberOfItems(int range)
        {
            // Arrange
            for (var i = 1; i <= range; i++)
            {
                _array.Add(i);
            }

            // Act
            var result = _array.Size;

            // Assert
            Assert.That(result, Is.EqualTo(range));
        }
Esempio n. 28
0
        static ChemicalBlock()
        {
            var list = new DynamicArray <IChemicalItem>(new IChemicalItem[] {
                new Cylinder("H₂"),
                new Cylinder("O₂"),
                new Cylinder("CO₂"),
                new Cylinder("CO"),
                new Cylinder("Cl₂"),
                new Cylinder("N₂"),
                new Cylinder("NH₃"),
                new Cylinder("NO₂"),
                new Cylinder("NO"),
                new Cylinder("N₂O"),
                new Cylinder("HCl"),
                new Cylinder("SO₂"),
                new Cylinder("H₂S"),
                new Cylinder("HF"),
                new Cylinder("PH₃"),
                new Cylinder("C₂H₂"),
                new Cylinder("(CN)₂"),
                new Cylinder("Cl₂O"),
                new Cylinder("ClO₂"),
                new PurePowder("Na₂O"),
                new PurePowder("Na₂O₂", Color.LightYellow),
                new PurePowder("MgO"),
                new PurePowder("Al₂O₃"),
                new PurePowder("K₂O"),
                new PurePowder("CaO"),
                new PurePowder("Cr₂O₃", Color.DarkGreen),
                new PurePowder("MnO", Color.Black),
                new PurePowder("MnO₂", Color.Black),
                new PurePowder("Fe₂O₃", Color.DarkRed),
                new PurePowder("Fe₃O₄", Color.Black),
                new PurePowder("CuO", Color.Black),
                new PurePowder("Cu₂O", Color.Red),
                new PurePowder("CuCl"),
                new PurePowder("ZnO"),
                new PurePowder("Ag₂O"),
                new PurePowder("HgO", new Color(227, 23, 13)),
                new PurePowder("PbO", Color.Yellow),
                new PurePowder("PbO₂", Color.Black),
                new PurePowder("CaC₂", new Color(25, 25, 25)),
                new PurePowder("Mg₃N₂", Color.LightYellow),
                new PurePowder("SiO₂"),
                new PurePowder("SiC", new Color(25, 25, 25)),
                new PurePowder("P₂O₅"),
                new PurePowder("P₄O₆"),
                new PurePowder("PCl₃"),
                new PurePowder("PCl₅"),
            });

            for (int i = 0; i < Cations.Length; i++)
            {
                AtomKind atom  = Cations[i].Array[0].Atom;
                Color    color = atom == AtomKind.Fe
                                        ? Cations[i].Charge == 2 ? Color.LightGreen : Color.DarkRed
                                        : atom == AtomKind.Cu ? Color.Blue : Color.White;
                for (int j = atom == AtomKind.Ag || Cations[i].Count == 2 ? 1 : 0; j < Anions.Length; j++)
                {
                    list.Add(new PurePowder(Cations[i] + Anions[j], color));
                }
            }
            list.Add(new PurePowder("H₂(SiO₃)"));
            list.Add(new PurePowder("Na₂(SiO₃)"));
            list.Add(new PurePowder("Mg(SiO₃)"));
            list.Add(new PurePowder("Ca(SiO₃)"));
            list.Add(new PurePowder("Na(HCO₃)"));
            list.Add(new PurePowder("Na₂S₂O₃"));
            list.Add(new PurePowder("Ca(ClO)₂"));
            list.Add(new PurePowder("Na(ClO₂)"));
            list.Add(new PurePowder("Mg(ClO₂)₂"));
            list.Add(new PurePowder("K(ClO₂)"));
            list.Add(new PurePowder("Ca(ClO₂)₂"));
            list.Add(new PurePowder("Ba(ClO₂)₂"));
            list.Add(new PurePowder("Na(ClO₃)"));
            list.Add(new PurePowder("Mg(ClO₃)₂"));
            list.Add(new PurePowder("K(ClO₃)"));
            list.Add(new PurePowder("Ca(ClO₃)₂"));
            list.Add(new PurePowder("Ba(ClO₃)₂"));
            list.Add(new PurePowder("Na(ClO₄)"));
            list.Add(new PurePowder("Mg(ClO₄)₂"));
            list.Add(new PurePowder("K(ClO₄)"));
            list.Add(new PurePowder("Ca(ClO₄)₂"));
            list.Add(new PurePowder("Ba(ClO₄)₂"));
            list.Add(new PurePowder("Na(CN)"));
            list.Add(new PurePowder("K(CN)"));
            list.Add(new PurePowder("Ca(CN)"));
            list.Add(new PurePowder("K₂(HPO₄)"));
            list.Add(new PurePowder("K(H₂PO₄)"));
            list.Add(new PurePowder("Na₂(HPO₄)"));
            list.Add(new PurePowder("Na(H₂PO₄)"));
            list.Add(new PurePowder("Na₂Cr₂O₇"));
            list.Add(new PurePowder("K₂Cr₂O₇"));
            list.Add(new PurePowder("Cu₃P"));
            list.Add(new PurePowder("NH₄H"));
            list.Add(new PurePowder("LiH"));
            list.Add(new PurePowder("NaH"));
            list.Add(new PurePowder("MgH₂"));
            //list.Add(new PurePowder("AlH₃"));
            list.Add(new PurePowder("KH"));
            list.Add(new PurePowder("CaH₂"));
            list.Add(new PurePowder("Na₃P"));
            //list.Add(new Cylinder("B₂H₆"));
            list.Add(new Cylinder("C₂H₄"));
            list.Capacity = list.m_count;
            Items         = list.Array;
        }
Esempio n. 29
0
        bool IPathNode.TryGetWalkableNeighbour(int dx, int dz, IUnitProperties unitProps, DynamicArray<IPathNode> neighbours)
        {
            var x = this.matrixPosX + dx;
            var z = this.matrixPosZ + dz;

            var neighbour = _parent[x, z];

            if (neighbour == null)
            {
                return false;
            }

            if (neighbour.isWalkableFrom(this, unitProps))
            {
                neighbours.Add(neighbour);
                return true;
            }

            return false;
        }
Esempio n. 30
0
 public void InsertTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>();
     Arr.Add(75);
     Arr.Add(51);
     Arr.Add(18);
     Arr.Insert(78, 2);
     Assert.AreEqual(Arr.Length, 4);
     Assert.AreEqual(Arr[2], 78);
     Assert.AreEqual(Arr[3], 18);
 }
Esempio n. 31
0
        public void FindSneakCollisionBoxes(Vector3 position, Vector2 overhang, DynamicArray <CollisionBox> result)
        {
            int num  = Terrain.ToCell(position.X);
            int num2 = Terrain.ToCell(position.Y);
            int num3 = Terrain.ToCell(position.Z);

            if (BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num, num2 - 1, num3)].IsCollidable)
            {
                return;
            }
            bool         num4 = position.X < (float)num + 0.5f;
            bool         flag = position.Z < (float)num3 + 0.5f;
            CollisionBox item;

            if (num4)
            {
                if (flag)
                {
                    bool isCollidable  = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num, num2 - 1, num3 - 1)].IsCollidable;
                    bool isCollidable2 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num - 1, num2 - 1, num3)].IsCollidable;
                    bool isCollidable3 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num - 1, num2 - 1, num3 - 1)].IsCollidable;
                    if ((isCollidable && !isCollidable2) || ((!isCollidable && !isCollidable2) & isCollidable3))
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3(num, num2, (float)num3 + overhang.Y), new Vector3(num + 1, num2 + 1, num3 + 1)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                    if ((!isCollidable && isCollidable2) || ((!isCollidable && !isCollidable2) & isCollidable3))
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3((float)num + overhang.X, num2, num3), new Vector3(num + 1, num2 + 1, num3 + 1)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                    if (isCollidable && isCollidable2)
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3((float)num + overhang.X, num2, (float)num3 + overhang.Y), new Vector3(num + 1, num2 + 1, num3 + 1)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                }
                else
                {
                    bool isCollidable4 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num, num2 - 1, num3 + 1)].IsCollidable;
                    bool isCollidable5 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num - 1, num2 - 1, num3)].IsCollidable;
                    bool isCollidable6 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num - 1, num2 - 1, num3 + 1)].IsCollidable;
                    if ((isCollidable4 && !isCollidable5) || ((!isCollidable4 && !isCollidable5) & isCollidable6))
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3(num, num2, num3), new Vector3(num + 1, num2 + 1, (float)(num3 + 1) - overhang.Y)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                    if ((!isCollidable4 && isCollidable5) || ((!isCollidable4 && !isCollidable5) & isCollidable6))
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3((float)num + overhang.X, num2, num3), new Vector3(num + 1, num2 + 1, num3 + 1)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                    if (isCollidable4 && isCollidable5)
                    {
                        item = new CollisionBox
                        {
                            Box        = new BoundingBox(new Vector3((float)num + overhang.X, num2, num3), new Vector3(num + 1, num2 + 1, (float)(num3 + 1) - overhang.Y)),
                            BlockValue = 0
                        };
                        result.Add(item);
                    }
                }
            }
            else if (flag)
            {
                bool isCollidable7 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num, num2 - 1, num3 - 1)].IsCollidable;
                bool isCollidable8 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num + 1, num2 - 1, num3)].IsCollidable;
                bool isCollidable9 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num + 1, num2 - 1, num3 - 1)].IsCollidable;
                if ((isCollidable7 && !isCollidable8) || ((!isCollidable7 && !isCollidable8) & isCollidable9))
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, (float)num3 + overhang.Y), new Vector3(num + 1, num2 + 1, num3 + 1)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
                if ((!isCollidable7 && isCollidable8) || ((!isCollidable7 && !isCollidable8) & isCollidable9))
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, num3), new Vector3((float)(num + 1) - overhang.X, num2 + 1, num3 + 1)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
                if (isCollidable7 && isCollidable8)
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, (float)num3 + overhang.Y), new Vector3((float)(num + 1) - overhang.X, num2 + 1, num3 + 1)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
            }
            else
            {
                bool isCollidable10 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num, num2 - 1, num3 + 1)].IsCollidable;
                bool isCollidable11 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num + 1, num2 - 1, num3)].IsCollidable;
                bool isCollidable12 = BlocksManager.Blocks[m_subsystemTerrain.Terrain.GetCellContents(num + 1, num2 - 1, num3 + 1)].IsCollidable;
                if ((isCollidable10 && !isCollidable11) || ((!isCollidable10 && !isCollidable11) & isCollidable12))
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, num3), new Vector3(num + 1, num2 + 1, (float)(num3 + 1) - overhang.Y)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
                if ((!isCollidable10 && isCollidable11) || ((!isCollidable10 && !isCollidable11) & isCollidable12))
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, num3), new Vector3((float)(num + 1) - overhang.X, num2 + 1, num3 + 1)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
                if (isCollidable10 && isCollidable11)
                {
                    item = new CollisionBox
                    {
                        Box        = new BoundingBox(new Vector3(num, num2, num3), new Vector3((float)(num + 1) - overhang.X, num2 + 1, (float)(num3 + 1) - overhang.Y)),
                        BlockValue = 0
                    };
                    result.Add(item);
                }
            }
        }
Esempio n. 32
0
        private void GetWalkableCellNeighbours(Cell cell, DynamicArray <Cell> walkableCells, bool preventDiagonals)
        {
            if (walkableCells.count != 0)
            {
                // if the list for holding the cells is not empty, make it empty
                walkableCells.Clear();
            }

            // prepare non-diagonal neighbours in all 4 directions (up, down, left, right)
            var n1 = GetCellNeighbour(cell, -1, 0);
            var n2 = GetCellNeighbour(cell, 0, -1);
            var n3 = GetCellNeighbour(cell, 1, 0);
            var n4 = GetCellNeighbour(cell, 0, 1);

            var unitAttributes = _unitProperties.attributes;

            bool lw = false, rw = false, uw = false, dw = false;

            if (n1 != null)
            {
                // check whether this neighbour has been fast marched
                lw = _fastMarchedCellsSet.ContainsKey(n1.position);
                if (!lw)
                {
                    // if the cell has not been fast marched...
                    if (n1.isWalkable(unitAttributes) && cell.isWalkableFrom(n1, _unitProperties))
                    {
                        // ... and the cell is walkable, then add it to the list
                        walkableCells.Add(n1);
                        lw = true;
                    }
                }
            }

            if (n2 != null)
            {
                dw = _fastMarchedCellsSet.ContainsKey(n2.position);
                if (!dw)
                {
                    if (n2.isWalkable(unitAttributes) && cell.isWalkableFrom(n2, _unitProperties))
                    {
                        walkableCells.Add(n2);
                        dw = true;
                    }
                }
            }

            if (n3 != null)
            {
                rw = _fastMarchedCellsSet.ContainsKey(n3.position);
                if (!rw)
                {
                    if (n3.isWalkable(unitAttributes) && cell.isWalkableFrom(n3, _unitProperties))
                    {
                        walkableCells.Add(n3);
                        rw = true;
                    }
                }
            }

            if (n4 != null)
            {
                uw = _fastMarchedCellsSet.ContainsKey(n4.position);
                if (!uw)
                {
                    if (n4.isWalkable(unitAttributes) && cell.isWalkableFrom(n4, _unitProperties))
                    {
                        walkableCells.Add(n4);
                        uw = true;
                    }
                }
            }

            if (preventDiagonals)
            {
                return;
            }

            bool urw, drw, dlw, ulw;

            if (_allowCornerCutting)
            {
                // if we allow corner cuttting, then just one of the neighbours need to be free to go diagonally
                urw = uw || rw;
                drw = dw || rw;
                dlw = dw || lw;
                ulw = uw || lw;
            }
            else
            {
                // however, if we don't allow corner cutting, then both neighbours need to be free to allow diagonal neighbour
                urw = uw && rw;
                drw = dw && rw;
                dlw = dw && lw;
                ulw = uw && lw;
            }

            if (dlw)
            {
                var n5 = GetCellNeighbour(cell, -1, -1);
                if (n5 != null && !_fastMarchedCellsSet.ContainsKey(n5.position))
                {
                    if (n5.isWalkable(unitAttributes) && cell.isWalkableFrom(n5, _unitProperties))
                    {
                        walkableCells.Add(n5);
                    }
                }
            }

            if (ulw)
            {
                var n6 = GetCellNeighbour(cell, -1, 1);
                if (n6 != null && !_fastMarchedCellsSet.ContainsKey(n6.position))
                {
                    if (n6.isWalkable(unitAttributes) && cell.isWalkableFrom(n6, _unitProperties))
                    {
                        walkableCells.Add(n6);
                    }
                }
            }

            if (drw)
            {
                var n7 = GetCellNeighbour(cell, 1, -1);
                if (n7 != null && !_fastMarchedCellsSet.ContainsKey(n7.position))
                {
                    if (n7.isWalkable(unitAttributes) && cell.isWalkableFrom(n7, _unitProperties))
                    {
                        walkableCells.Add(n7);
                    }
                }
            }

            if (urw)
            {
                var n8 = GetCellNeighbour(cell, 1, 1);
                if (n8 != null && !_fastMarchedCellsSet.ContainsKey(n8.position))
                {
                    if (n8.isWalkable(unitAttributes) && cell.isWalkableFrom(n8, _unitProperties))
                    {
                        walkableCells.Add(n8);
                    }
                }
            }
        }
Esempio n. 33
0
        public static PlainShape MakeCentroidNet(this Delaunay self, Allocator allocator, long minArea = 0, bool onlyConvex = false)
        {
            int n = self.triangles.Count;

            var details = new NativeArray <Detail>(n, Allocator.Temp);

            for (int i = 0; i < n; ++i)
            {
                var triangle = self.triangles[i];
                var count    = 0;
                if (triangle.nA >= 0)
                {
                    ++count;
                }

                if (triangle.nB >= 0)
                {
                    ++count;
                }

                if (triangle.nC >= 0)
                {
                    ++count;
                }

                details[i] = new Detail(triangle.Center(), count);
            }

            int capacity = self.points.Count;

            var visitedIndex = new NativeArray <bool>(capacity, Allocator.Temp);
            var result       = new DynamicPlainShape(8 * capacity, capacity, allocator);
            var forePoints   = new NativeArray <IntVector>(4, Allocator.Temp);
            var path         = new DynamicArray <IntVector>(8, Allocator.Temp);
            var subPath      = new DynamicArray <IntVector>(8, Allocator.Temp);

            for (int i = 0; i < n; ++i)
            {
                var triangle = self.triangles[i];
                var detail   = details[i];

                for (int j = 0; j <= 2; ++j)
                {
                    var v = triangle.Vertex(j);
                    if (visitedIndex[v.index])
                    {
                        continue;
                    }

                    visitedIndex[v.index] = true;

                    if (v.isPath)
                    {
                        if (detail.count == 1 && triangle.Neighbor(j) >= 0)
                        {
                            switch (j)
                            {
                            case 0:     // a
                                var ab0 = v.point.Center(triangle.vB.point);
                                var ca0 = v.point.Center(triangle.vC.point);

                                forePoints[0] = v.point;
                                forePoints[1] = ab0;
                                forePoints[2] = detail.center;
                                forePoints[3] = ca0;
                                break;

                            case 1:     // b
                                var bc1 = v.point.Center(point: triangle.vC.point);
                                var ab1 = v.point.Center(point: triangle.vA.point);

                                forePoints[0] = v.point;
                                forePoints[1] = bc1;
                                forePoints[2] = detail.center;
                                forePoints[3] = ab1;
                                break;

                            default:     // c
                                var ca2 = v.point.Center(point: triangle.vA.point);
                                var bc2 = v.point.Center(point: triangle.vB.point);

                                forePoints[0] = v.point;
                                forePoints[1] = ca2;
                                forePoints[2] = detail.center;
                                forePoints[3] = bc2;
                                break;
                            }

                            if (minArea == 0 || forePoints.Area() > minArea)
                            {
                                result.Add(forePoints, true);
                            }
                        }
                        else
                        {
                            path.RemoveAll();
                            // first going in a counterclockwise direction
                            var current = triangle;
                            int k       = triangle.FindIndex(v.index);
                            int right   = (k + 2) % 3;
                            var prev    = triangle.Neighbor(right);
                            while (prev >= 0)
                            {
                                var prevTriangle = self.triangles[prev];
                                k = prevTriangle.FindIndex(v.index);
                                if (k < 0)
                                {
                                    break;
                                }

                                current = prevTriangle;
                                path.Add(details[prev].center);

                                right = (k + 2) % 3;
                                prev  = current.Neighbor(right);
                            }

                            var left         = (k + 1) % 3;
                            var lastPrevPair = current.Vertex(left).point;
                            path.Add(lastPrevPair.Center(v.point));

                            path.array.Reverse();

                            path.Add(details[i].center);

                            // now going in a clockwise direction
                            current = triangle;
                            k       = triangle.FindIndex(v.index);
                            left    = (k + 1) % 3;
                            var next = triangle.Neighbor(left);
                            while (next >= 0)
                            {
                                var nextTriangle = self.triangles[next];
                                k = nextTriangle.FindIndex(v.index);
                                if (k < 0)
                                {
                                    break;
                                }

                                current = nextTriangle;
                                path.Add(details[next].center);
                                left = (k + 1) % 3;
                                next = current.Neighbor(left);
                            }

                            right = (k + 2) % 3;
                            var lastNextPair = current.Vertex(right).point;
                            path.Add(lastNextPair.Center(v.point));

                            if (onlyConvex)
                            {
                                // split path into convex subPath
                                var c  = v.point;
                                var p0 = path[0];
                                var v0 = p0 - c;
                                var d0 = v0;

                                subPath.RemoveAll();

                                subPath.Add(c);
                                subPath.Add(path[0]);
                                for (int t = 1; t < path.Count; ++t)
                                {
                                    var p1 = path[t];
                                    var d1 = p1 - p0;
                                    var v1 = p1 - c;
                                    if (v0.CrossProduct(v1) <= 0 && d0.CrossProduct(d1) <= 0)
                                    {
                                        subPath.Add(p1);
                                    }
                                    else
                                    {
                                        if (minArea == 0 || subPath.slice.Area() > minArea)
                                        {
                                            result.Add(subPath.slice, true);
                                        }
                                        subPath.RemoveAll();
                                        subPath.Add(c);
                                        subPath.Add(p0);
                                        subPath.Add(p1);
                                        v0 = p0 - c;
                                    }

                                    p0 = p1;
                                    d0 = d1;
                                }

                                if (minArea == 0 || subPath.slice.Area() > minArea)
                                {
                                    result.Add(subPath.slice, true);
                                }
                            }
                            else
                            {
                                path.Add(v.point);
                                if (minArea == 0 || path.slice.Area() > minArea)
                                {
                                    result.Add(path.slice, true);
                                }
                            }
                        }
                    }
                    else
                    {
                        path.RemoveAll();
                        int start = i;
                        var next  = start;
                        do
                        {
                            var t      = self.triangles[next];
                            var center = details[next].center;
                            path.Add(center);
                            int index = (t.FindIndex(v.index) + 1) % 3;
                            next = t.Neighbor(index);
                        } while (next != start && next >= 0);
                        if (minArea == 0 || path.slice.Area() > minArea)
                        {
                            result.Add(path.slice, true);
                        }
                    }
                }
            }

            path.Dispose();
            subPath.Dispose();
            forePoints.Dispose();
            details.Dispose();
            visitedIndex.Dispose();

            return(result.Convert());
        }
Esempio n. 34
0
        internal static void Load()
        {
            Items = new Item[] {
                new RottenEgg(),
                new MetalLine(Materials.Iron),
                new MetalLine(Materials.Copper),
                new MetalLine(Materials.Steel),
                new MetalLine(Materials.Gold),
                new MetalLine(Materials.Silver),
                new MetalLine(Materials.Platinum),
                new MetalLine(Materials.Lead),
                new MetalLine(Materials.Stannary),
                new MetalLine(Materials.Chromium),
                new MetalLine(Materials.Aluminum),
                new MetalLine(Materials.FeAlCrAlloy),
                new Resistor(Materials.FeAlCrAlloy),
                new Rod("RifleBarrel", "Rifle Barrel are made by Rifling Machine. They are useful for making guns.", Color.Gray),
                new ScrapIron(),
                new OreChunk(Matrix.CreateRotationX(4f) * Matrix.CreateRotationZ(2f), Matrix.CreateTranslation(32 % 16 / 16f, 32 / 16 / 16f, 0f), Color.White, false, Materials.Gold),
                new OreChunk(Matrix.CreateRotationX(5f) * Matrix.CreateRotationZ(2f), Matrix.CreateTranslation(33 % 16 / 16f, 33 / 16 / 16f, 0f), Color.White, false, Materials.Silver),
                new OreChunk(Matrix.CreateRotationX(6f) * Matrix.CreateRotationZ(2f), Matrix.CreateTranslation(34 % 16 / 16f, 34 / 16 / 16f, 0f), Color.White, false, Materials.Platinum),
                new OreChunk(Matrix.CreateRotationX(1f) * Matrix.CreateRotationZ(3f), Matrix.CreateTranslation(35 % 16 / 16f, 35 / 16 / 16f, 0f), Color.LightGray, false, Materials.Lead),
                new OreChunk(Matrix.CreateRotationX(1f) * Matrix.CreateRotationZ(4f), Matrix.CreateTranslation(36 % 16 / 16f, 36 / 16 / 16f, 0f), new Color(65, 224, 205), false, Materials.Zinc),
                new OreChunk(Matrix.CreateRotationX(1f) * Matrix.CreateRotationZ(5f), Matrix.CreateTranslation(37 % 16 / 16f, 37 / 16 / 16f, 0f), new Color(225, 225, 225), false, Materials.Stannary),
                new OreChunk(Matrix.CreateRotationX(1f) * Matrix.CreateRotationZ(6f), Matrix.CreateTranslation(38 % 16 / 16f, 38 / 16 / 16f, 0f), Color.White, false, Materials.Mercury),
                new OreChunk(Matrix.CreateRotationX(1f) * Matrix.CreateRotationZ(7f), Matrix.CreateTranslation(39 % 16 / 16f, 39 / 16 / 16f, 0f), Color.White, false, Materials.Chromium),
                new OreChunk(Matrix.CreateRotationX(2f) * Matrix.CreateRotationZ(-1f), Matrix.CreateTranslation(40 % 16 / 16f, 40 / 16 / 16f, 0f), new Color(190, 190, 190), false, Materials.Titanium),
                new OreChunk(Matrix.CreateRotationX(3f) * Matrix.CreateRotationZ(-1f), Matrix.CreateTranslation(41 % 16 / 16f, 41 / 16 / 16f, 0f), Color.White, false, Materials.Nickel),
                new MetalIngot(Materials.Steel),
                new MetalIngot(Materials.Gold),
                new MetalIngot(Materials.Silver),
                new MetalIngot(Materials.Platinum),
                new MetalIngot(Materials.Lead),
                new MetalIngot(Materials.Zinc),
                new MetalIngot(Materials.Nickel),
                new MetalIngot(Materials.Chromium),
                new MetalIngot(Materials.Aluminum),
                new MetalIngot(Materials.Stannary),
                new MetalIngot(Materials.FeAlCrAlloy),
                new Powder(Materials.Iron),
                new Powder(Materials.Copper),
                new Powder(Materials.Germanium),
                new Powder(Materials.Gold),
                new Powder(Materials.Silver),
                new Powder(Materials.Platinum),
                new Powder(Materials.Lead),
                new Powder(Materials.Stannary),
                new Powder(Materials.Zinc),
                new Powder(Materials.Chromium),
                new Powder(Materials.Nickel),
                new Powder(Materials.Aluminum),
                new CoalPowder("Coal", new Color(28, 28, 28)),
                new CoalPowder("CokeCoal", Color.DarkGray, 2000f, 100f, "Coke Coal Powder looks like silver powder obtained by crushing coke coal. It can be used to be fuel or the reductant agent in the industrial field."),
                new Plate(Materials.Steel),
                new Plate(Materials.Iron),
                new Plate(Materials.Copper),
                new Plate(Materials.Gold),
                new Plate(Materials.Silver),
                new Plate(Materials.Lead),
                new Plate(Materials.Zinc),
                new Plate(Materials.Stannary),
                new Plate(Materials.Platinum),
                new Plate(Materials.Aluminum),
                new SteamBoat(),
                new Train(),
                new Rod(Materials.Steel, Color.LightGray),
                new Rod(Materials.Copper, new Color(255, 127, 80)),
                new Rod(Materials.Gold, new Color(255, 215, 0)),
                new Rod(Materials.Silver, new Color(253, 253, 253)),
                new Rod(Materials.Lead, new Color(88, 87, 86)),
                new Rod(Materials.Platinum, new Color(253, 253, 253)),
                new Rod(Materials.Zinc, new Color(232, 232, 232)),
                new Rod(Materials.Stannary, new Color(232, 232, 232)),
                new Rod(Materials.Chromium, new Color(90, 90, 90)),
                new Rod(Materials.Titanium, new Color(253, 253, 253)),
                new Rod(Materials.Nickel, new Color(253, 253, 253)),
                new Rod(Materials.Aluminum, new Color(232, 232, 232)),
                new Mould("Gear", Matrix.CreateTranslation(new Vector3(0.5f)) * 2f, Matrix.CreateTranslation(4f, 3.8f, 0f), "A gear made of steel, the neccessary part of all the machine during the initial industrial era."),
                new Mould("Wheel", Matrix.CreateTranslation(new Vector3(0.5f)) * 1.2f, Matrix.CreateTranslation(4f, 3.8f, 0f), "A wheel made of steel, the neccessary part of the steam engine train.", 2f),
                new Mould("WheelMould", Matrix.CreateTranslation(0f, -0.02f, 0f) * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(2.6f, 1.4f, 0f), "A wheel mould made of dirt and sand, the neccessary part in making steel wheel.", 1.6f),
                new Mould("GearMould", Matrix.CreateTranslation(0f, -0.02f, 0f) * 1.6f * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(2.6f, 1.4f, 0f), "A gear mould made of dirt and sand, the neccessary part in making steel gear."),
                new Mould("Models/Piston", "Piston", Matrix.CreateTranslation(0.5f, 0.3f, 0.5f) * 1.2f, Matrix.CreateTranslation(4f, 3.8f, 0f), "A piston made of iron, copper and steel, the neccessary part of many machine.", "IndustrialPiston", 1.6f),
                new Wire("CopperWire"),
                new Sheet(Materials.Steel),
                new Sheet(Materials.Iron),
                new Sheet(Materials.Copper),
                new Sheet(Materials.Gold),
                new Sheet(Materials.Silver),
                new Sheet(Materials.Lead),
                new Sheet(Materials.Zinc),
                new Sheet(Materials.Stannary),
                new Sheet(Materials.Platinum),
                new Sheet(Materials.Aluminum),
                new Mould("Models/Battery", "Battery", Matrix.CreateRotationX(MathUtils.PI / 2) * Matrix.CreateTranslation(0.5f, 0.5f, 0f), Matrix.CreateTranslation(9f / 16f, -7f / 16f, 0f) * Matrix.CreateScale(20f), "工业磁铁", "IndustrialMagnet"),
                new RefractoryBrick(),
                new CokeCoal(),
                new Fan(Materials.Steel),
                new Fan(Materials.Aluminum),
                new Carriage(),
                new Airship(),
                new Sheet(Materials.Titanium),
                new CoalPowder("Sulphur", Color.Yellow, 1500f, 30f, "Sulphur is powder obtained by crushing sulphur chunk."),
                new Powder("煤灰", new Color(25, 25, 25)),
                new Powder("矿渣", new Color(25, 25, 25)),
                new Powder("木屑", Color.LightYellow),
                new Powder("碎砖", Color.DarkRed),
                new Powder("碎玻璃", Color.White),
                new Cylinder(Matrix.CreateScale(70f)),
                new Cylinder(Matrix.CreateScale(70f), "液化石油气"),
                new Cylinder(Matrix.CreateScale(70f), "液化天然气"),
                new Cylinder(Matrix.CreateScale(40f, 80f, 40f), "He"),
                new Cylinder(Matrix.CreateScale(40f, 80f, 40f), "Ar"),
                new Powder("粗盐", Color.White),
                new Powder("精盐", Color.White),
                new Powder("酵母", Color.White),
                new Powder("粗硅", Color.DarkGray),
                new Powder("明矾", Color.White),
                new Powder("石英砂", Color.White),
                new Powder("苔粉", Color.DarkGreen),
                new GranulatedItem("滑石", Color.White),
                new Powder("滑石粉", Color.White),
                new Sheet("多晶硅", Color.DarkGray),
                new Sheet("单晶硅", Color.DarkGray),
                new FlatItem
                {
                    DefaultTextureSlot = 122,
                    DefaultDisplayName = "基因查看器"
                },
                new Screwdriver(Color.White),
                new Wrench(Color.White),
                new ABomb(),
                new HBomb(),
                new Powder("聚乙烯", Color.White),
                new Powder("聚丙烯", Color.White),
                new Plate("聚乙烯板", Color.White),
                new Sheet("聚乙烯片", Color.White),
                new Sheet("128K RAM", Color.DarkGreen),
                new Sheet("256K RAM", Color.DarkGreen),
                new Sheet("512K RAM", Color.DarkGreen),
                new Sheet("Intel 4004", Color.DarkGray),
                new Sheet("Intel 8008", Color.DarkGray),
                new Sheet("Intel 8086", Color.DarkGray),
                new Sheet("TMX 1795", Color.DarkGray),
            };
            ElementBlock.Devices = new Device[]
            {
                new Fridge(),
                new Generator(),
                new Magnetizer(),
                new Separator(),
                new AirBlower(),
                new WireDevice(),
                new EFurnace(),
                new Canpack(),
                new Electrobath(),                 //8
                new Battery(Matrix.CreateTranslation(0f, -0.5f, 0f) * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(11f / 16f, 4f / 256f, 0f), "Cu-Zn电池", "Cu-Zn电池", "CuZnBattery"),
                new Battery(Matrix.CreateTranslation(0f, -0.5f, 0f) * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(11f / 16f, 4f / 256f, 0f), "Ag-Zn电池", "Ag-Zn电池", "AgZnBattery"),
                new Battery(Matrix.CreateTranslation(0f, -0.5f, 0f) * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(11f / 16f, 4f / 256f, 0f), "Au-Zn电池", "Au-Zn电池", "AuZnBattery"),
                new Battery(Matrix.CreateTranslation(0f, -0.5f, 0f) * Matrix.CreateTranslation(new Vector3(0.5f)), Matrix.CreateTranslation(-2f / 16f, 4f / 16f, 0f), "伏打电池", "伏打电池", "VBattery"),
                new Pipe(),
                new Pipe(1),
                new Pipe(2),
                new Pipe(3),
                new Pipe(4),
                new Pipe(5),
                new Pipe(6),
                new Pipe(7),
                new AirCompressor(),
                new UThickener(),
                new TEDC(),
            };
            int i;

            IdTable = new Dictionary <string, int>(Items.Length);
            for (i = 0; i < Items.Length; i++)
            {
                IdTable.Add(Items[i].GetCraftingId(), Index | i << 14);
            }
            for (i = 0; i < ElementBlock.Devices.Length; i++)
            {
                IdTable.Add(ElementBlock.Devices[i].GetCraftingId(), ElementBlock.Index | i << 14);
            }
            var list = new DynamicArray <Item>(GunpowderBlock.Items)
            {
                Capacity = GunpowderBlock.Items.Length
            };

            for (i = 0; i < 2048; i++)
            {
                list.Add(new Mine((MineType)(i & 63), (i >> 6) / 4.0));
            }
            list.Capacity        = list.Count;
            GunpowderBlock.Items = list.Array;
            for (i = 1; i < GunpowderBlock.Items.Length; i++)
            {
                IdTable.Add(GunpowderBlock.Items[i].GetCraftingId(), GunpowderBlock.Index | i << 14);
            }

            /*var stream = Utils.GetTargetFile("IndustrialEquations.txt");
             * Equation.Reactions = new HashSet<Equation>();
             * try
             * {
             *      var reader = new StreamReader(stream);
             *      while (true)
             *      {
             *              var line = reader.ReadLine();
             *              if (line == null) break;
             *              Equation.Reactions.Add(Equation.Parse(line));
             *      }
             * }
             * finally
             * {
             *      stream.Close();
             * }*/
            var stream = Utils.GetTargetFile("IndustrialMod_en-us.lng", false);

            if (stream == null)
            {
                return;
            }
            try
            {
                Utils.ReadKeyValueFile(Utils.TR, stream);
            }
            finally
            {
                stream.Close();
            }
        }
 static void Main(string[] args)
 {
     DynamicArray<int> dyn = new DynamicArray<int>();
     dyn.Add(5);
     dyn.Add(7);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Add(5);
     dyn.Print();
     dyn.RemoveAt(4);
     Console.WriteLine(dyn.Contains(7));
 }
Esempio n. 36
0
 public void FailIndexToSmall()
 {
     var target = new DynamicArray<int>();
     target.Add(5);
     var badIndex = target[-1];
 }
        /// <summary>
        /// Gets the walkable cell neighbours - used in fast marching.
        /// </summary>
        private void GetWalkableCellNeighbours(Cell cell, DynamicArray <Cell> walkableCells, bool preventDiagonals)
        {
            if (walkableCells.count != 0)
            {
                // if the list for holding the cells is not empty, make it empty
                walkableCells.Clear();
            }

            int mx = cell.matrixPosX;
            int mz = cell.matrixPosZ;

            // prepare non-diagonal neighbours in all 4 directions (up, down, left, right)
            var n1 = _grid.cellMatrix[mx - 1, mz];
            var n2 = _grid.cellMatrix[mx, mz - 1];
            var n3 = _grid.cellMatrix[mx + 1, mz];
            var n4 = _grid.cellMatrix[mx, mz + 1];

            bool lw = false, rw = false, uw = false, dw = false;

            if (n1 != null)
            {
                // check whether this neighbour has been fast marched
                lw = _fastMarchedCells[mx - 1, mz].sqrMagnitude != 0f;
                if (!lw)
                {
                    // if the cell has not been fast marched...
                    if (n1.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n1, _unitProperties))
                    {
                        // and the cell is walkable, then add it to the list
                        walkableCells.Add(n1);
                        lw = true;
                    }
                }
            }

            if (n2 != null)
            {
                dw = _fastMarchedCells[mx, mz - 1].sqrMagnitude != 0f;
                if (!dw)
                {
                    if (n2.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n2, _unitProperties))
                    {
                        walkableCells.Add(n2);
                        dw = true;
                    }
                }
            }

            if (n3 != null)
            {
                rw = _fastMarchedCells[mx + 1, mz].sqrMagnitude != 0f;
                if (!rw)
                {
                    if (n3.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n3, _unitProperties))
                    {
                        walkableCells.Add(n3);
                        rw = true;
                    }
                }
            }

            if (n4 != null)
            {
                uw = _fastMarchedCells[mx, mz + 1].sqrMagnitude != 0f;
                if (!uw)
                {
                    if (n4.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n4, _unitProperties))
                    {
                        walkableCells.Add(n4);
                        uw = true;
                    }
                }
            }

            if (preventDiagonals)
            {
                return;
            }

            bool urw, drw, dlw, ulw;

            if (_allowCornerCutting)
            {
                // if we allow corner cuttting, then just one of the neighbours need to be free to go diagonally
                urw = uw || rw;
                drw = dw || rw;
                dlw = dw || lw;
                ulw = uw || lw;
            }
            else
            {
                // however, if we don't allow corner cutting, then both neighbours need to be free to allow diagonal neighbour
                urw = uw && rw;
                drw = dw && rw;
                dlw = dw && lw;
                ulw = uw && lw;
            }

            if (dlw)
            {
                var n5 = _grid.cellMatrix[mx - 1, mz - 1];
                if (n5 != null && _fastMarchedCells[mx - 1, mz - 1].sqrMagnitude == 0f)
                {
                    if (n5.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n5, _unitProperties))
                    {
                        walkableCells.Add(n5);
                    }
                }
            }

            if (ulw)
            {
                var n6 = _grid.cellMatrix[mx - 1, mz + 1];
                if (n6 != null && _fastMarchedCells[mx - 1, mz + 1].sqrMagnitude == 0f)
                {
                    if (n6.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n6, _unitProperties))
                    {
                        walkableCells.Add(n6);
                    }
                }
            }

            if (drw)
            {
                var n7 = _grid.cellMatrix[mx + 1, mz - 1];
                if (n7 != null && _fastMarchedCells[mx + 1, mz - 1].sqrMagnitude == 0f)
                {
                    if (n7.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n7, _unitProperties))
                    {
                        walkableCells.Add(n7);
                    }
                }
            }

            if (urw)
            {
                var n8 = _grid.cellMatrix[mx + 1, mz + 1];
                if (n8 != null && _fastMarchedCells[mx + 1, mz + 1].sqrMagnitude == 0f)
                {
                    if (n8.IsWalkableWithClearance(_unitProperties) && cell.IsWalkableFromWithClearance(n8, _unitProperties))
                    {
                        walkableCells.Add(n8);
                    }
                }
            }
        }
        private bool GetCellNeighboursAndUnwalkability(Cell cell, DynamicArray<Cell> walkableCells, bool preventDiagonals)
        {
            if (walkableCells.count != 0)
            {
                // if the list for holding the cells is not empty, make it empty
                walkableCells.Clear();
            }

            var unitAttributes = _unitProperties.attributes;

            int mx = cell.matrixPosX;
            int mz = cell.matrixPosZ;

            for (int x = -1; x <= 1; x++)
            {
                for (int z = -1; z <= 1; z++)
                {
                    if (x == 0 && z == 0)
                    {
                        // cell in the middle is the cell which neighbours we want, thus ignore the center cell
                        continue;
                    }

                    if (x != 0 && z != 0 && preventDiagonals)
                    {
                        // if we are supposed to prevent diagonal moves, then ignore diagonal cell neighbours
                        continue;
                    }

                    var neighbour = _grid.cellMatrix[mx + x, mz + z];
                    if (neighbour != null)
                    {
                        if (neighbour.isWalkable(unitAttributes) && cell.isWalkableFrom(neighbour, _unitProperties))
                        {
                            // if the neighbour is walkable, and the center cell is walkable from this neighbour, then it is of interest
                            walkableCells.Add(neighbour);
                        }
                        else
                        {
                            // if we find just a single neighbour that is blocked, then we return false
                            return false;
                        }
                    }
                    else if (_builtInContainment)
                    {
                        // if there is a missing cell, and we want to use built-in containment, then return false on first missing cell (off-grid)
                        return false;
                    }
                }
            }

            return true;
        }
Esempio n. 39
0
        public void AppendImageExtrusion(Image image, Rectangle bounds, Vector3 size, Color color)
        {
            BlockMesh blockMesh = new BlockMesh();
            DynamicArray <BlockMeshVertex> vertices = blockMesh.Vertices;
            DynamicArray <ushort>          indices  = blockMesh.Indices;
            BlockMeshVertex item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Left, bounds.Top, -1f),
                TextureCoordinates = new Vector2(bounds.Left, bounds.Top)
            };

            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Right, bounds.Top, -1f),
                TextureCoordinates = new Vector2(bounds.Right, bounds.Top)
            };
            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Left, bounds.Bottom, -1f),
                TextureCoordinates = new Vector2(bounds.Left, bounds.Bottom)
            };
            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Right, bounds.Bottom, -1f),
                TextureCoordinates = new Vector2(bounds.Right, bounds.Bottom)
            };
            vertices.Add(item);
            indices.Add((ushort)(vertices.Count - 4));
            indices.Add((ushort)(vertices.Count - 1));
            indices.Add((ushort)(vertices.Count - 3));
            indices.Add((ushort)(vertices.Count - 1));
            indices.Add((ushort)(vertices.Count - 4));
            indices.Add((ushort)(vertices.Count - 2));
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Left, bounds.Top, 1f),
                TextureCoordinates = new Vector2(bounds.Left, bounds.Top)
            };
            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Right, bounds.Top, 1f),
                TextureCoordinates = new Vector2(bounds.Right, bounds.Top)
            };
            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Left, bounds.Bottom, 1f),
                TextureCoordinates = new Vector2(bounds.Left, bounds.Bottom)
            };
            vertices.Add(item);
            item = new BlockMeshVertex
            {
                Position           = new Vector3(bounds.Right, bounds.Bottom, 1f),
                TextureCoordinates = new Vector2(bounds.Right, bounds.Bottom)
            };
            vertices.Add(item);
            indices.Add((ushort)(vertices.Count - 4));
            indices.Add((ushort)(vertices.Count - 3));
            indices.Add((ushort)(vertices.Count - 1));
            indices.Add((ushort)(vertices.Count - 1));
            indices.Add((ushort)(vertices.Count - 2));
            indices.Add((ushort)(vertices.Count - 4));
            for (int i = bounds.Left - 1; i <= bounds.Right; i++)
            {
                int num = -1;
                for (int j = bounds.Top - 1; j <= bounds.Bottom; j++)
                {
                    bool num2 = !bounds.Contains(new Point2(i, j)) || image.GetPixel(i, j) == Color.Transparent;
                    bool flag = bounds.Contains(new Point2(i - 1, j)) && image.GetPixel(i - 1, j) != Color.Transparent;
                    if (num2 & flag)
                    {
                        if (num < 0)
                        {
                            num = j;
                        }
                    }
                    else if (num >= 0)
                    {
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)i - 0.01f, (float)num - 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)(i - 1) + 0.01f, (float)num + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)i - 0.01f, (float)num - 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)i - 0.01f, (float)num + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)i - 0.01f, (float)j + 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)(i - 1) + 0.01f, (float)j - 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)i - 0.01f, (float)j + 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)i - 0.01f, (float)j - 0.01f)
                        };
                        vertices.Add(item);
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 3));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 2));
                        num = -1;
                    }
                }
            }
            for (int k = bounds.Left - 1; k <= bounds.Right; k++)
            {
                int num3 = -1;
                for (int l = bounds.Top - 1; l <= bounds.Bottom; l++)
                {
                    bool num4  = !bounds.Contains(new Point2(k, l)) || image.GetPixel(k, l) == Color.Transparent;
                    bool flag2 = bounds.Contains(new Point2(k + 1, l)) && image.GetPixel(k + 1, l) != Color.Transparent;
                    if (num4 & flag2)
                    {
                        if (num3 < 0)
                        {
                            num3 = l;
                        }
                    }
                    else if (num3 >= 0)
                    {
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)(k + 1) + 0.01f, (float)num3 - 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)(k + 1) + 0.01f, (float)num3 + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)(k + 1) + 0.01f, (float)num3 - 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)(k + 2) - 0.01f, (float)num3 + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)(k + 1) + 0.01f, (float)l + 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)(k + 1) + 0.01f, (float)l - 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)(k + 1) + 0.01f, (float)l + 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)(k + 2) - 0.01f, (float)l - 0.01f)
                        };
                        vertices.Add(item);
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 3));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 2));
                        indices.Add((ushort)(vertices.Count - 4));
                        num3 = -1;
                    }
                }
            }
            for (int m = bounds.Top - 1; m <= bounds.Bottom; m++)
            {
                int num5 = -1;
                for (int n = bounds.Left - 1; n <= bounds.Right; n++)
                {
                    bool num6  = !bounds.Contains(new Point2(n, m)) || image.GetPixel(n, m) == Color.Transparent;
                    bool flag3 = bounds.Contains(new Point2(n, m - 1)) && image.GetPixel(n, m - 1) != Color.Transparent;
                    if (num6 & flag3)
                    {
                        if (num5 < 0)
                        {
                            num5 = n;
                        }
                    }
                    else if (num5 >= 0)
                    {
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num5 - 0.01f, (float)m - 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)num5 + 0.01f, (float)(m - 1) + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num5 - 0.01f, (float)m - 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)num5 + 0.01f, (float)m - 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)n + 0.01f, (float)m - 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)n - 0.01f, (float)(m - 1) + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)n + 0.01f, (float)m - 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)n - 0.01f, (float)m - 0.01f)
                        };
                        vertices.Add(item);
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 3));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 2));
                        indices.Add((ushort)(vertices.Count - 4));
                        num5 = -1;
                    }
                }
            }
            for (int num7 = bounds.Top - 1; num7 <= bounds.Bottom; num7++)
            {
                int num8 = -1;
                for (int num9 = bounds.Left - 1; num9 <= bounds.Right; num9++)
                {
                    bool num10 = !bounds.Contains(new Point2(num9, num7)) || image.GetPixel(num9, num7) == Color.Transparent;
                    bool flag4 = bounds.Contains(new Point2(num9, num7 + 1)) && image.GetPixel(num9, num7 + 1) != Color.Transparent;
                    if (num10 & flag4)
                    {
                        if (num8 < 0)
                        {
                            num8 = num9;
                        }
                    }
                    else if (num8 >= 0)
                    {
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num8 - 0.01f, (float)(num7 + 1) + 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)num8 + 0.01f, (float)(num7 + 1) + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num8 - 0.01f, (float)(num7 + 1) + 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)num8 + 0.01f, (float)(num7 + 2) - 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num9 + 0.01f, (float)(num7 + 1) + 0.01f, -1.01f),
                            TextureCoordinates = new Vector2((float)num9 - 0.01f, (float)(num7 + 1) + 0.01f)
                        };
                        vertices.Add(item);
                        item = new BlockMeshVertex
                        {
                            Position           = new Vector3((float)num9 + 0.01f, (float)(num7 + 1) + 0.01f, 1.01f),
                            TextureCoordinates = new Vector2((float)num9 - 0.01f, (float)(num7 + 2) - 0.01f)
                        };
                        vertices.Add(item);
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 3));
                        indices.Add((ushort)(vertices.Count - 1));
                        indices.Add((ushort)(vertices.Count - 4));
                        indices.Add((ushort)(vertices.Count - 2));
                        num8 = -1;
                    }
                }
            }
            for (int num11 = 0; num11 < vertices.Count; num11++)
            {
                vertices.Array[num11].Position.X           -= (float)bounds.Left + (float)bounds.Width / 2f;
                vertices.Array[num11].Position.Y            = (float)bounds.Bottom - vertices.Array[num11].Position.Y - (float)bounds.Height / 2f;
                vertices.Array[num11].Position.X           *= size.X / (float)bounds.Width;
                vertices.Array[num11].Position.Y           *= size.Y / (float)bounds.Height;
                vertices.Array[num11].Position.Z           *= size.Z / 2f;
                vertices.Array[num11].TextureCoordinates.X /= image.Width;
                vertices.Array[num11].TextureCoordinates.Y /= image.Height;
                vertices.Array[num11].Color = color;
            }
            AppendBlockMesh(blockMesh);
        }
Esempio n. 40
0
        public void CalculateTemperature(int x, int y, int z, float meterTemperature, float meterInsulation, out float temperature, out float temperatureFlux)
        {
            m_toVisit.Clear();
            for (int i = 0; i < m_visited.Length; i++)
            {
                m_visited[i] = 0;
            }
            float num  = 0f;
            float num2 = 0f;
            float num3 = 0f;
            float num4 = 0f;
            float num5 = 0f;
            float num6 = 0f;

            m_toVisit.Add(133152);
            for (int j = 0; j < m_toVisit.Count; j++)
            {
                int num7 = m_toVisit.Array[j];
                if ((m_visited[num7 / 32] & (1 << num7)) != 0)
                {
                    continue;
                }
                m_visited[num7 / 32] |= 1 << num7;
                int          num8        = (num7 & 0x3F) - 32;
                int          num9        = ((num7 >> 6) & 0x3F) - 32;
                int          num10       = ((num7 >> 12) & 0x3F) - 32;
                int          num11       = num8 + x;
                int          num12       = num9 + y;
                int          num13       = num10 + z;
                Terrain      terrain     = base.SubsystemTerrain.Terrain;
                TerrainChunk chunkAtCell = terrain.GetChunkAtCell(num11, num13);
                if (chunkAtCell == null || num12 < 0 || num12 >= 256)
                {
                    continue;
                }
                int   x2            = num11 & 0xF;
                int   y2            = num12;
                int   z2            = num13 & 0xF;
                int   cellValueFast = chunkAtCell.GetCellValueFast(x2, y2, z2);
                int   num14         = Terrain.ExtractContents(cellValueFast);
                Block block         = BlocksManager.Blocks[num14];
                float heat          = GetHeat(cellValueFast);
                if (heat > 0f)
                {
                    int   num15 = MathUtils.Abs(num8) + MathUtils.Abs(num9) + MathUtils.Abs(num10);
                    int   num16 = (num15 <= 0) ? 1 : (4 * num15 * num15 + 2);
                    float num17 = 1f / (float)num16;
                    num5 += num17 * 36f * heat;
                    num6 += num17;
                }
                else if (block.IsHeatBlocker(cellValueFast))
                {
                    int   num18 = MathUtils.Abs(num8) + MathUtils.Abs(num9) + MathUtils.Abs(num10);
                    int   num19 = (num18 <= 0) ? 1 : (4 * num18 * num18 + 2);
                    float num20 = 1f / (float)num19;
                    float num21 = terrain.SeasonTemperature;
                    float num22 = SubsystemWeather.GetTemperatureAdjustmentAtHeight(y2);
                    float num23 = (block is WaterBlock) ? (MathUtils.Max((float)chunkAtCell.GetTemperatureFast(x2, z2) + num21 - 6f, 0f) + num22) : ((!(block is IceBlock)) ? ((float)chunkAtCell.GetTemperatureFast(x2, z2) + num21 + num22) : (0f + num21 + num22));
                    num  += num20 * num23;
                    num2 += num20;
                }
                else if (y >= chunkAtCell.GetTopHeightFast(x2, z2))
                {
                    int   num24 = MathUtils.Abs(num8) + MathUtils.Abs(num9) + MathUtils.Abs(num10);
                    int   num25 = (num24 <= 0) ? 1 : (4 * num24 * num24 + 2);
                    float num26 = 1f / (float)num25;
                    PrecipitationShaftInfo precipitationShaftInfo = m_subsystemWeather.GetPrecipitationShaftInfo(x, z);
                    float num27 = terrain.SeasonTemperature;
                    float num28 = (y >= precipitationShaftInfo.YLimit) ? MathUtils.Lerp(0f, -2f, precipitationShaftInfo.Intensity) : 0f;
                    float num29 = MathUtils.Lerp(-6f, 0f, m_subsystemSky.SkyLightIntensity);
                    float num30 = SubsystemWeather.GetTemperatureAdjustmentAtHeight(y2);
                    num3 += num26 * ((float)chunkAtCell.GetTemperatureFast(x2, z2) + num27 + num28 + num29 + num30);
                    num4 += num26;
                }
                else if (m_toVisit.Count < 4090)
                {
                    if (num8 > -30)
                    {
                        m_toVisit.Add(num7 - 1);
                    }
                    if (num8 < 30)
                    {
                        m_toVisit.Add(num7 + 1);
                    }
                    if (num9 > -30)
                    {
                        m_toVisit.Add(num7 - 64);
                    }
                    if (num9 < 30)
                    {
                        m_toVisit.Add(num7 + 64);
                    }
                    if (num10 > -30)
                    {
                        m_toVisit.Add(num7 - 4096);
                    }
                    if (num10 < 30)
                    {
                        m_toVisit.Add(num7 + 4096);
                    }
                }
            }
            float num31 = 0f;

            for (int k = -7; k <= 7; k++)
            {
                for (int l = -7; l <= 7; l++)
                {
                    TerrainChunk chunkAtCell2 = base.SubsystemTerrain.Terrain.GetChunkAtCell(x + k, z + l);
                    if (chunkAtCell2 == null || chunkAtCell2.State < TerrainChunkState.InvalidVertices1)
                    {
                        continue;
                    }
                    for (int m = -7; m <= 7; m++)
                    {
                        int num32 = k * k + m * m + l * l;
                        if (num32 > 49 || num32 <= 0)
                        {
                            continue;
                        }
                        int x3    = (x + k) & 0xF;
                        int num33 = y + m;
                        int z3    = (z + l) & 0xF;
                        if (num33 >= 0 && num33 < 256)
                        {
                            float heat2 = GetHeat(chunkAtCell2.GetCellValueFast(x3, num33, z3));
                            if (heat2 > 0f && !base.SubsystemTerrain.Raycast(new Vector3(x, y, z) + new Vector3(0.5f, 0.75f, 0.5f), new Vector3(x + k, y + m, z + l) + new Vector3(0.5f, 0.75f, 0.5f), useInteractionBoxes: false, skipAirBlocks: true, delegate(int raycastValue, float d)
                            {
                                Block block2 = BlocksManager.Blocks[Terrain.ExtractContents(raycastValue)];
                                return(block2.IsCollidable && !block2.IsTransparent);
                            }).HasValue)
                            {
                                num31 += heat2 * 3f / (float)(num32 + 2);
                            }
                        }
                    }
                }
            }
            float num34 = 0f;
            float num35 = 0f;

            if (num31 > 0f)
            {
                float num36 = 3f * num31;
                num34 += 35f * num36;
                num35 += num36;
            }
            if (num2 > 0f)
            {
                float num37 = 1f;
                num34 += num / num2 * num37;
                num35 += num37;
            }
            if (num4 > 0f)
            {
                float num38 = 4f * MathUtils.Pow(num4, 0.25f);
                num34 += num3 / num4 * num38;
                num35 += num38;
            }
            if (num6 > 0f)
            {
                float num39 = 1.5f * MathUtils.Pow(num6, 0.25f);
                num34 += num5 / num6 * num39;
                num35 += num39;
            }
            if (meterInsulation > 0f)
            {
                num34 += meterTemperature * meterInsulation;
                num35 += meterInsulation;
            }
            temperature     = ((num35 > 0f) ? (num34 / num35) : meterTemperature);
            temperatureFlux = num35 - meterInsulation;
        }
        void IPathNode.GetWalkableNeighbours(DynamicArray<IPathNode> neighbours, IUnitProperties unitProps, bool cornerCuttingAllowed, bool preventDiagonalMoves)
        {
            var destinationNodes = _partner._neighbourNodes;
            var nodeCount = destinationNodes.Length;
            var unitAttributes = unitProps.attributes;

            if (_parentPortal.type == PortalType.Connector)
            {
                //This logic depends on the prerequisite that connector portals always a only one cell wide or high, such that the cells covered by the portal represents a simple array.
                //The prerequisite also demands that connector portals are symmetric and placed directly across from one another, the cannot be offset, e.g. cell one on one side must link to cell one on the other side.
                //We then simply find the index of the cell being evaluated (the portal predecessor) and only return maximum 3 cell on the other side, its immediate partner plus each diagonal if they exist.
                //  _______________
                // |___|_N_|_N_|_N_|
                // |___|___|_P_|___|
                //
                //This accomplished two things, First of all we reduce the number of cells being evaluated. Second the resulting path will cross the portal as quickly as possible and not make long diagonal moves across a portal.
                var p = ((IPathNode)this).predecessor;
                var idx = _matrixBounds.IndexOf(p.matrixPosX, p.matrixPosZ);
                if (idx < 0)
                {
                    return;
                }

                var start = Math.Max(idx - 1, 0);
                var end = Math.Min(idx + 2, nodeCount);

                for (int i = start; i < end; i++)
                {
                    if (destinationNodes[i].isWalkable(unitAttributes))
                    {
                        neighbours.Add(destinationNodes[i]);
                    }
                }
            }
            else
            {
                for (int i = 0; i < nodeCount; i++)
                {
                    if (destinationNodes[i].isWalkable(unitAttributes))
                    {
                        neighbours.Add(destinationNodes[i]);
                    }
                }
            }
        }
Esempio n. 42
0
        public static void ConsoleInterface()
        {
            var array = new DynamicArray <int>();
            var list  = new List <int>();

            Console.WriteLine("List elements: ");
            for (int i = 0; i < 10; i++)
            {
                list.Add(i % 3 + 1);
                Console.Write(list[i] + ",");
            }

            for (int i = 0; i < 10; i++)
            {
                array.Add(i % 4 + 1);
                Console.WriteLine("Adding " + array[i] + ":" + Environment.NewLine +
                                  "Dynamic array length: " + array.Length + Environment.NewLine +
                                  "Dynamic array capacity: " + array.Capacity);
            }
            Console.WriteLine(Environment.NewLine + "Dynamic array elements: ");
            foreach (var item in array)
            {
                Console.Write(item + ",");
            }
            Console.WriteLine(Environment.NewLine + "Array after removing item = 1:");
            if (array.Remove(1))
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("There is no such item!");
            }
            foreach (var item in array)
            {
                Console.Write(item + ",");
            }
            Console.WriteLine("Dynamic array length: " + array.Length + Environment.NewLine +
                              "Dynamic array capacity: " + array.Capacity);
            Console.WriteLine("Adding a list to the dynamic array:");
            array.AddRange(list);
            foreach (var item in array)
            {
                Console.Write(item + ",");
            }
            Console.WriteLine("Dynamic array length: " + array.Length + Environment.NewLine +
                              "Dynamic array capacity: " + array.Capacity);
            Console.WriteLine(Environment.NewLine + "Array after insertion of item = 9 at 9th position:");
            if (array.Insert(9, 9))
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("Failure!");
            }
            foreach (var item in array)
            {
                Console.Write(item + ",");
            }
            Console.WriteLine("Dynamic array length: " + array.Length + Environment.NewLine +
                              "Dynamic array capacity: " + array.Capacity);
        }
Esempio n. 43
0
        static void Main(string[] args)
        {
            Console.WriteLine("###      LinkedList tests");

            var list = new LinkedList<string>();
            list.Add("x");
            list.Add("g");
            list.Add("s");

            Console.WriteLine(list.Count); //output: 3

            list.InsertAfter("g", "a");
            list.InsertAt(10, "z");
            list.InsertAt(2, "z");
            list.Remove("z");
            list[1] = "m";

            foreach (string value in list)
            {
                Console.WriteLine(value);
            }
            //output:
            //x
            //m
            //a
            //s

            Console.WriteLine("\n###      DynamicArray tests");

            var dArray = new DynamicArray<string>();
            dArray.Add("x");
            dArray.Add("g");
            dArray.Add("s");

            Console.WriteLine(dArray.Count); //output: 3

            dArray.InsertAt(10, "z");
            dArray.InsertAt(2, "z");
            dArray.Remove("z");
            dArray[1] = "m";

            for (int i = 0; i < dArray.Count; i++)
            {
                Console.WriteLine(dArray[i]);
            }
            //output:
            //x
            //m
            //a
            //s

            Console.WriteLine("\n###      Map tests");

            var map = new Map<int, string>();

            map.Add(1, "a");
            map.Add(2, "a");
            map.Add(3, "s");

            Console.WriteLine(map.Count); //output: 3

            try
            {
                map.Add(2, "v");
            }
            catch (ArgumentException argEx)
            {
                Console.WriteLine(argEx.Message); //exception message
            }

            Console.WriteLine(map.ContainsKey(2)); //output: True
            Console.WriteLine(map.ContainsValue("a")); //output: True
            map.Remove(2);
            Console.WriteLine(map.ContainsKey(2)); //output: False
            Console.WriteLine(map.ContainsValue("a")); //output: True

            Console.WriteLine(map.Count); //output: 2

            Console.WriteLine("\n###      HashMap tests");

            var hashMap = new Map<int, string>();

            hashMap.Add(1, "a");
            hashMap.Add(2, "a");
            hashMap.Add(3, "s");

            Console.WriteLine(hashMap.Count); //output: 3

            try
            {
                hashMap.Add(2, "v");
            }
            catch (ArgumentException argEx)
            {
                Console.WriteLine(argEx.Message); //exception message
            }

            Console.WriteLine(hashMap.ContainsKey(2)); //output: True
            Console.WriteLine(hashMap.ContainsValue("a")); //output: True
            hashMap.Remove(2);
            Console.WriteLine(hashMap.ContainsKey(2)); //output: False
            Console.WriteLine(hashMap.ContainsValue("a")); //output: True

            Console.WriteLine(hashMap.Count); //output: 2
        }
Esempio n. 44
0
        public override void GenerateTerrainVertices(BlockGeometryGenerator generator, TerrainGeometry geometry, int value, int x, int y, int z)
        {
            TerrainGeometrySubset        subsetAlphaTest = geometry.SubsetAlphaTest;
            DynamicArray <TerrainVertex> vertices        = subsetAlphaTest.Vertices;
            DynamicArray <ushort>        indices         = subsetAlphaTest.Indices;
            int   count        = vertices.Count;
            int   data         = Terrain.ExtractData(value);
            int   num          = Terrain.ExtractLight(value);
            int   mountingFace = GetMountingFace(data);
            float s            = LightingManager.LightIntensityByLightValueAndFace[num + 16 * mountingFace];
            Color color        = Color.White * s;

            switch (mountingFace)
            {
            case 2:
                vertices.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z + 1, color, DefaultTextureSlot, 0, ref vertices.Array[count]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z + 1, color, DefaultTextureSlot, 1, ref vertices.Array[count + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z + 1, color, DefaultTextureSlot, 2, ref vertices.Array[count + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z + 1, color, DefaultTextureSlot, 3, ref vertices.Array[count + 3]);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)count);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)(count + 2));
                break;

            case 3:
                vertices.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z, color, DefaultTextureSlot, 0, ref vertices.Array[count]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z, color, DefaultTextureSlot, 3, ref vertices.Array[count + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z + 1, color, DefaultTextureSlot, 2, ref vertices.Array[count + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z + 1, color, DefaultTextureSlot, 1, ref vertices.Array[count + 3]);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)count);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)(count + 2));
                break;

            case 0:
                vertices.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z, color, DefaultTextureSlot, 0, ref vertices.Array[count]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y, z, color, DefaultTextureSlot, 1, ref vertices.Array[count + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x + 1, y + 1, z, color, DefaultTextureSlot, 2, ref vertices.Array[count + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z, color, DefaultTextureSlot, 3, ref vertices.Array[count + 3]);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                break;

            case 1:
                vertices.Count += 4;
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z, color, DefaultTextureSlot, 0, ref vertices.Array[count]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z, color, DefaultTextureSlot, 3, ref vertices.Array[count + 1]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y + 1, z + 1, color, DefaultTextureSlot, 2, ref vertices.Array[count + 2]);
                BlockGeometryGenerator.SetupLitCornerVertex(x, y, z + 1, color, DefaultTextureSlot, 1, ref vertices.Array[count + 3]);
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 1));
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)(count + 3));
                indices.Add((ushort)count);
                indices.Add((ushort)(count + 2));
                break;
            }
        }
Esempio n. 45
0
        static void Main(string[] args)
        {
            DynamicArray <int> array = new DynamicArray <int>();

            array.Add(1);
            array.Add(2);
            array.Add(3);
            array.Add(4);
            array.Add(5);
            array.Add(6);
            array.Add(7);
            array.Add(8);
            WriteLine("Исходный массив:");
            foreach (var item in array)
            {
                Write(item + "   ");
            }
            WriteLine();
            WriteLine("Свойство Capacity: " + array.Capacity);
            WriteLine("Свойство Length: " + array.Length);
            WriteLine();
            WriteLine("Применение Add:");
            array.Add(9);
            foreach (var item in array)
            {
                Write(item + "   ");
            }
            WriteLine();
            WriteLine("Свойство Capacity: " + array.Capacity);
            WriteLine("Свойство Length: " + array.Length);
            WriteLine();
            WriteLine("Применение AddRange:");
            array.AddRange(new int[] { 10, 11 });
            foreach (var item in array)
            {
                Console.Write(item + "   ");
            }
            WriteLine();
            WriteLine("Свойство Capacity: " + array.Capacity);
            WriteLine("Свойство Length: " + array.Length);
            WriteLine();
            WriteLine("Применение Remove:");
            array.Remove(9);
            foreach (var item in array)
            {
                Write(item + "   ");
            }
            WriteLine();
            WriteLine("Свойство Capacity: " + array.Capacity);
            WriteLine("Свойство Length: " + array.Length);
            WriteLine();
            WriteLine("Применение Insert:");
            array.Insert(2, 5);
            foreach (var item in array)
            {
                Write(item + "   ");
            }
            WriteLine();
            WriteLine("Свойство Capacity: " + array.Capacity);
            WriteLine("Свойство Length: " + array.Length);
            WriteLine();
            WriteLine("Применение ToArray:");
            int[] array2 = array.ToArray();
            for (int i = 0; i < array2.Length; i++)
            {
                Write(array2[i] + "   ");
            }
            WriteLine();

            ReadKey();
        }
Esempio n. 46
0
    {           // Демонстрация работы с DynamicArray, написано ужасно, но как лучше не знаю.
        static void Main()
        {
            Console.WriteLine("Демонстрация работы бибоиотеки Dynamic_Array");
            DynamicArray <int> da = new DynamicArray <int>();

            Console.WriteLine($"Создание экземпляра DynamicArray конструктором без параметров, вместимость: {da.Capacity}");
            DynamicArray <int> da2 = new DynamicArray <int>(4);

            Console.WriteLine($"Создание экземпляра DynamicArray конструктором с параметром 4, вместимость: {da2.Capacity}");
            List <int> lst1 = new List <int> {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            DynamicArray <int> da3 = new DynamicArray <int>(lst1);

            Console.WriteLine($"Создание экземпляра DynamicArray конструктором принимающим на вход другую коллекцию IEnumerable\n" +
                              $"Длина коллекции List: {lst1.Count}, вместимость: {lst1.Capacity}, содержимое: {string.Join(", ", lst1)};\n" +
                              $"Длина коллекции DynamicArray: {da3.Count}, вместимость: {da3.Capacity}, содержимое: {da3}");
            Console.WriteLine("Метод Add, позволяющий добавлять в конец массива новые данные. При нехватке места для добавления элемента массив удваивается: ");
            int count = 1;

            while (count < 6)
            {
                da2.Add(count);
                Console.WriteLine($"Колличество элементов: {da2.Count}, вместимость: {da2.Capacity}, коллекция {da2}");
                count++;
            }
            Console.WriteLine($"Метод AddRange добавляющий в конец массива содержимое коллекции IEnumerable. Содержимое коллекции da2 до добавления lst1: {da2}, вместимость: {da2.Capacity}");
            da2.AddRange(lst1);
            Console.WriteLine($"Метод AddRange добавляющий в конец массива содержимое коллекции IEnumerable. Содержимое коллекции da2 после добавления lst1: {da2}, вместимость: {da2.Capacity}");
            da2.Remove(5);
            Console.WriteLine($"Метод Remove удаляющий из коллекции пепрвое вхождение заданного элемента (5). Содержимое коллекции da2 после удаления 5: {da2}, вместимость: {da2.Capacity}");
            da2.Insert(4, 5);
            da2.Insert(4, 5);
            Console.WriteLine($"Метод Insert, позволяющую вставить объект по нужному индексу Содержимое коллекции da2 после двойного добавления 5: {da2}, вместимость: {da2.Capacity}");
            Console.WriteLine($"Свйойство Lenght - получение колличества элементов (В данном случае Count): {da2.Count}, вместимость: {da2.Capacity}");
            Console.WriteLine("Реализация IEnumerable и Ienumerable<T>");
            foreach (int i in da3)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("Реализация доступа по индексу");
            for (int i = 0; i < da3.Count; i++)
            {
                Console.WriteLine(da3[i]);
            }

            try
            {
                Console.WriteLine(da3[10]);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine($"Демонстрация ошибки при доступе мимо индекса: {ex.Message}");
            }

            Console.WriteLine("Доступ к элементам с конца, при использовании отрицательного индекса:");

            count = -1;
            while (count >= da3.Count * -1)
            {
                Console.WriteLine($"Индекс: {count}; содержимое: {da3[count]}");
                count--;
            }

            Console.WriteLine($"Метод ToArray возввращающий обычный массив: {string.Join(", ", da3.ToArray())}");

            DynamicArray <int> da4 = da3.Clone() as DynamicArray <int>;

            Console.WriteLine($"Реализация интерфейса IClonable: {string.Join(", ", da4)}");

            Console.WriteLine($"Перегрузка оператора Equals: {da3.Equals(da4)}, ==, {da3 == da4}");

            CycledDynamicArray <int> cycledArray = new CycledDynamicArray <int>(da3);

            Console.WriteLine("Массив CycledDynamicArray на базе DynamicArray с зацикленным итератором:");
            count = 0;

            foreach (int i in cycledArray)
            {
                Console.WriteLine(i);
                count++;
                if (count > 30)
                {
                    break;
                }
            }

            Console.WriteLine("Перерыв");

            count = 0;

            foreach (int i in cycledArray)
            {
                Console.WriteLine(i);
                count++;
                if (count > 30)
                {
                    break;
                }
            }

            Console.WriteLine("Демонстрация работы метода расширения ToDynamicArray:");

            List <int> list1 = new List <int> {
                1, 2, 3
            };
            List <int> list2 = new List <int> {
                4, 5, 6
            };
            DynamicArray <int> customArray = list1.Concat(list2).ToDynamicArray();

            foreach (int i in customArray)
            {
                Console.WriteLine("!" + i);
            }

            DynamicArray <int> da5 = new DynamicArray <int>(new int[] { 7, 7, 7 });


            int[] mass = da3.ToArray();

            da5.CopyTo(mass, 6);

            Console.WriteLine($"Работа метода CopyTo: {string.Join(", ", mass)}");

            // Работа с InsertWithFeedback:
            Console.WriteLine(da5.InsertWithFeedback(4, 1));
            Console.WriteLine(da5);

            Console.ReadLine();
        }
Esempio n. 47
0
 public void FailIndexToLarge()
 {
     var target = new DynamicArray<int>();
     target.Add(5);
     var badIndex = target[2];
 }
Esempio n. 48
0
 public void InsertInFullListTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>(2);
     Arr.Add(91);
     Arr.Add(36);
     Arr.Insert(46, 1);
     Assert.AreEqual(Arr.Length, 3);
     Assert.AreEqual(Arr.Capacity, 4);
     Assert.AreEqual(Arr[1], 46);
     Assert.AreEqual(Arr[2], 36);
 }
Esempio n. 49
0
 public void RemoveExistingElementTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>(2);
     Arr.Add(99);
     Arr.Add(90);
     Assert.AreEqual(Arr.Remove(90), true);
     Assert.AreEqual(Arr.Length, 1);
 }
Esempio n. 50
0
 public void RemoveNotexistingElementTest()
 {
     DynamicArray<int> Arr = new DynamicArray<int>(2);
     Arr.Add(21);
     Arr.Add(26);
     Assert.AreEqual(Arr.Remove(87), false);
 }
        private void GetWalkableCellNeighbours(Cell cell, DynamicArray<Cell> walkableCells, bool preventDiagonals)
        {
            if (walkableCells.count != 0)
            {
                // if the list for holding the cells is not empty, make it empty
                walkableCells.Clear();
            }

            int mx = cell.matrixPosX;
            int mz = cell.matrixPosZ;

            // prepare non-diagonal neighbours in all 4 directions (up, down, left, right)
            var n1 = _grid.cellMatrix[mx - 1, mz];
            var n2 = _grid.cellMatrix[mx, mz - 1];
            var n3 = _grid.cellMatrix[mx + 1, mz];
            var n4 = _grid.cellMatrix[mx, mz + 1];

            var unitAttributes = _unitProperties.attributes;

            bool lw = false, rw = false, uw = false, dw = false;

            if (n1 != null)
            {
                // check whether this neighbour has been fast marched
                lw = _fastMarchedCellsSet.ContainsKey(n1.position);
                if (!lw)
                {
                    // if the cell has not been fast marched...
                    if (n1.isWalkable(unitAttributes) && cell.isWalkableFrom(n1, _unitProperties))
                    {
                        // ... and the cell is walkable, then add it to the list
                        walkableCells.Add(n1);
                        lw = true;
                    }
                }
            }

            if (n2 != null)
            {
                dw = _fastMarchedCellsSet.ContainsKey(n2.position);
                if (!dw)
                {
                    if (n2.isWalkable(unitAttributes) && cell.isWalkableFrom(n2, _unitProperties))
                    {
                        walkableCells.Add(n2);
                        dw = true;
                    }
                }
            }

            if (n3 != null)
            {
                rw = _fastMarchedCellsSet.ContainsKey(n3.position);
                if (!rw)
                {
                    if (n3.isWalkable(unitAttributes) && cell.isWalkableFrom(n3, _unitProperties))
                    {
                        walkableCells.Add(n3);
                        rw = true;
                    }
                }
            }

            if (n4 != null)
            {
                uw = _fastMarchedCellsSet.ContainsKey(n4.position);
                if (!uw)
                {
                    if (n4.isWalkable(unitAttributes) && cell.isWalkableFrom(n4, _unitProperties))
                    {
                        walkableCells.Add(n4);
                        uw = true;
                    }
                }
            }

            if (preventDiagonals)
            {
                return;
            }

            bool urw, drw, dlw, ulw;
            if (_allowCornerCutting)
            {
                // if we allow corner cuttting, then just one of the neighbours need to be free to go diagonally
                urw = uw || rw;
                drw = dw || rw;
                dlw = dw || lw;
                ulw = uw || lw;
            }
            else
            {
                // however, if we don't allow corner cutting, then both neighbours need to be free to allow diagonal neighbour
                urw = uw && rw;
                drw = dw && rw;
                dlw = dw && lw;
                ulw = uw && lw;
            }

            if (dlw)
            {
                var n5 = _grid.cellMatrix[mx - 1, mz - 1];
                if (n5 != null && !_fastMarchedCellsSet.ContainsKey(n5.position))
                {
                    if (n5.isWalkable(unitAttributes) && cell.isWalkableFrom(n5, _unitProperties))
                    {
                        walkableCells.Add(n5);
                    }
                }
            }

            if (ulw)
            {
                var n6 = _grid.cellMatrix[mx - 1, mz + 1];
                if (n6 != null && !_fastMarchedCellsSet.ContainsKey(n6.position))
                {
                    if (n6.isWalkable(unitAttributes) && cell.isWalkableFrom(n6, _unitProperties))
                    {
                        walkableCells.Add(n6);
                    }
                }
            }

            if (drw)
            {
                var n7 = _grid.cellMatrix[mx + 1, mz - 1];
                if (n7 != null && !_fastMarchedCellsSet.ContainsKey(n7.position))
                {
                    if (n7.isWalkable(unitAttributes) && cell.isWalkableFrom(n7, _unitProperties))
                    {
                        walkableCells.Add(n7);
                    }
                }
            }

            if (urw)
            {
                var n8 = _grid.cellMatrix[mx + 1, mz + 1];
                if (n8 != null && !_fastMarchedCellsSet.ContainsKey(n8.position))
                {
                    if (n8.isWalkable(unitAttributes) && cell.isWalkableFrom(n8, _unitProperties))
                    {
                        walkableCells.Add(n8);
                    }
                }
            }
        }
Esempio n. 52
0
 void IPathNode.GetWalkableNeighbours(DynamicArray<IPathNode> neighbours, IUnitProperties unitProps, bool cornerCuttingAllowed, bool preventDiagonalMoves)
 {
     var destinationNodes = _partner._neighbourNodes;
     var nodeCount = destinationNodes.Length;
     var unitAttributes = unitProps.attributes;
     for (int i = 0; i < nodeCount; i++)
     {
         if (destinationNodes[i].isWalkable(unitAttributes))
         {
             neighbours.Add(destinationNodes[i]);
         }
     }
 }