示例#1
0
        /// <summary>
        /// Sends out all Commands
        /// </summary>
        public static void SendOut()
        {
            if (outCommands.Count > 0)
            {
                bufferedBytes.FastClear();

                for (int i = 0; i < outCommands.Count; i++)
                {
                    bufferedBytes.AddRange(outCommands [i].Serialized);
                }
                if (bufferedBytes.Count > 0)
                {
                    ClientManager.Distribute(bufferedBytes.ToArray());
                }

                outCommands.FastClear();
            }
        }
示例#2
0
        public void Setup(IAgentData interfacer)
        {
            gameObject.SetActive(true);
            LoadComponents();

            GameObject.DontDestroyOnLoad(gameObject);

            setupAbilitys.FastClear();

            MyAgentCode  = interfacer.Name;
            Data         = interfacer;
            SpawnVersion = 1;
            CheckCasting = true;

            Influencer = new LSInfluencer();
            if (_visualCenter == null)
            {
                _visualCenter = CachedTransform;
            }

            if (Animator.IsNotNull())
            {
                Animator.Setup();
            }


            abilityManager.Setup(this);
            Ringer = RingController.Create();
            if (Ringer.IsNotNull())
            {
                Ringer.Setup(this);
            }

            Influencer.Setup(this);
            Body.Setup(this);

            SelectionRadiusSquared = _selectionRadius * _selectionRadius;
            if (StatsBarer != null)
            {
                StatsBarer.Setup(this);
            }

            this.RegisterLockstep();
        }
示例#3
0
        void UpdateCoordinates()
        {
            const long gridSpacing = FixedMath.One;

            bufferCoordinates.FastClear();
            CachedBody.GetCoveredSnappedPositions(gridSpacing, bufferCoordinates);
            foreach (Vector2d vec in bufferCoordinates)
            {
                GridNode node = GridManager.GetNode(vec.x, vec.y);

                if (node == null)
                {
                    continue;
                }

                node.AddObstacle();
                LastCoordinates.Add(node);
            }
        }
示例#4
0
        public void Initialize()
        {
            Diplomacy.FastClear();
            for (int i = 0; i < TeamManager.Teams.Count; i++)
            {
                Team team = TeamManager.Teams[i];
                if (team != this)
                {
                    this.SetAllegiance(team, AllegianceType.Neutral);
                }
            }
            TeamManager.UpdateDiplomacy(this);

            TeamManager.Teams.Add(this);
            this.SetAllegiance(this, AllegianceType.Friendly);

            MainController = AgentController.Create();
            MainController.JoinTeam(this);
        }
 public static bool FindPath(Vector2d Start, Vector2d End, FastList <Vector2d> outputVectorPath)
 {
     if (!GetPathNodes(Start.x, Start.y, End.x, End.y, out node1, out node2))
     {
         return(false);
     }
     if (FindPath(node1, node2, OutputPath))
     {
         outputVectorPath.FastClear();
         length = OutputPath.Count - 1;
         for (i = 0; i < length; i++)
         {
             outputVectorPath.Add(OutputPath [i].WorldPos);
         }
         outputVectorPath.Add(End);
         return(true);
     }
     return(false);
 }
        public static void Simulate()
        {
            if (Offline)
            {
                ReceivedBytes.AddRange(BitConverter.GetBytes(LockstepManager.FrameCount));
                for (i = 0; i < OutCommands.Count; i++)
                {
                    ReceivedBytes.AddRange(OutCommands [i].Serialized);
                }
                AllReceivedBytes.AddRange(BitConverter.GetBytes(ReceivedBytes.Count));
                AllReceivedBytes.AddRange(ReceivedBytes);
            }
            else
            {
            }



            int frameCount = BitConverter.ToInt32(ReceivedBytes.innerArray, 0);

            Index = 4;

            FrameManager.EnsureCapacity(frameCount + 1);

            Frame frame;

            if (!FrameManager.HasFrame [frameCount])
            {
                frame = new Frame();
                FrameManager.AddFrame(frameCount, frame);

                while (Index < ReceivedBytes.Count)
                {
                    Command com = new Command();
                    Index += com.Reconstruct(ReceivedBytes.innerArray, Index);
                    frame.AddCommand(com);
                }
            }

            ReceivedBytes.FastClear();
            OutCommands.FastClear();
        }
        public static IEnumerator StreamPlayback(Replay playbackReplay)
        {
            int lastFrameByteCount = 0;
            int playbackPosition   = 0;

            byte[] playbackBytes = playbackReplay.Content;

            bool getNextStream = true;
            int  frameCount    = 0;
            int  nextFrame     = -1;


            yield return(null);

            FrameManager.EndFrame = playbackReplay.LastCommandedFrameCount;

            while (playbackPosition < playbackBytes.Length || frameCount <= nextFrame)
            {
                if (getNextStream == true)
                {
                    bufferBytes.FastClear();
                    lastFrameByteCount = (int)BitConverter.ToUInt16(playbackBytes, playbackPosition);
                    playbackPosition  += 2;
                    nextFrame          = BitConverter.ToInt32(playbackBytes, playbackPosition);
                    bufferBytes.AddRange(playbackBytes, playbackPosition, lastFrameByteCount);
                    playbackPosition += lastFrameByteCount;
                    getNextStream     = false;
                }

                if (nextFrame == frameCount)
                {
                    getNextStream = true;
                    CommandManager.ProcessPacket(bufferBytes);
                }
                else
                {
                    CommandManager.ProcessPacket(BitConverter.GetBytes(frameCount));
                }
                frameCount++;
            }
            yield break;
        }
示例#8
0
        static IEnumerator Tick()
        {
            float accumulator = 0;

            while (true)
            {
                if (IsSimulating && LockstepManager.GameStarted)
                {
                    bufferBytes.FastClear();
                    bufferBytes.AddRange(BitConverter.GetBytes(InfluenceFrameCount));
                    InfluenceFrameCount++;
                    bufferBytes.AddRange(receivedBytes);
                    receivedBytes.FastClear();
                    Send(bufferBytes.ToArray());
                }
                accumulator = 0;
                yield return(LSUtility.WaitRealTime(LockstepManager.BaseDeltaTime * LockstepManager.InfluenceResolution));
            }
            yield break;
        }
        public static bool FindPath(Vector2d End, GridNode startNode, GridNode endNode, FastList <Vector2d> outputVectorPath)
        {
            if (startNode.Unwalkable || endNode.Unwalkable)
            {
                return(false);
            }
            if (FindPath(startNode, endNode, OutputPath))
            {
                outputVectorPath.FastClear();
                length = OutputPath.Count - 1;
                for (i = 0; i < length; i++)
                {
                    outputVectorPath.Add(OutputPath [i].WorldPos);
                }
                outputVectorPath.Add(End);

                return(true);
            }
            return(false);
        }
示例#10
0
        public void RaycastMove(Vector3d delta)
        {
#if true
            Vector3d nextPosition = this.Position;
            nextPosition.Add(ref delta);
            HitBodies.FastClear();
            foreach (LSBody body in Raycaster.RaycastAll(this.Position, nextPosition))
            {
                if (this.BodyConditional(body))
                {
                    HitBodies.Add(body);
                }
            }
            if (HitBodies.Count > 0)
            {
                Hit();
            }
            this.Position = nextPosition;
#endif
        }
示例#11
0
        public static bool FindPath(Vector2d Start, Vector2d End, FastList <Vector2d> outputVectorPath, int unitSize = 1)
        {
            bool canAddEnd = false;

            if (!GetPathNodes(Start.x, Start.y, End.x, End.y, out node1, out node2, out canAddEnd))
            {
                return(false);
            }
            if (!NeedsPath(node1, node2, unitSize))
            {
                if (canAddEnd)
                {
                    outputVectorPath.Add(End);
                }
                else
                {
                    outputVectorPath.Add(node2.WorldPos);
                }
                return(true);
            }

            if (FindPath(node1, node2, OutputPath, unitSize))
            {
                outputVectorPath.FastClear();
                length = OutputPath.Count;
                for (i = 0; i < length; i++)
                {
                    outputVectorPath.Add(OutputPath[i].WorldPos);
                }
                if (canAddEnd)
                {
                    outputVectorPath.Add(End);
                }
                else
                {
                    outputVectorPath.Add(node2.WorldPos);
                }
                return(true);
            }
            return(false);
        }
示例#12
0
        private void Serialize()
        {
            Data.FastClear();
            ushort highestID = 0;

            for (int i = 0; i < selectedAgentLocalIDs.Count; i++)
            {
                ushort id = selectedAgentLocalIDs[i];
                if (id > highestID)
                {
                    highestID = id;
                }
            }
            int headerLength = (highestID + 1 - 1) / 8 + 1;

            Header = new BitArray(headerLength, false);
            for (int i = 0; i < selectedAgentLocalIDs.Count; i++)
            {
                SerializeID(selectedAgentLocalIDs[i]);
            }
        }
示例#13
0
        public static void Initialize()
        {
            CollisionIterationCount  = CollisionIterationSpread;
            CollisionIterationMark   = 0;
            CollisionIterationRemain = 0;
            PeakCount = 0;

            CachedIDs.FastClear();
            Array.Clear(SimObjects, 0, SimObjects.Length);
            Array.Clear(SimObjectExists, 0, SimObjectExists.Length);
            Array.Clear(CollisionPairs, 0, CollisionPairs.Length);

            CachedIDs.Clear();
            PeakCount        = 0;
            AssimilatedCount = 0;

            CollisionPairCount = 0;
            FastCollisionPairs.FastClear();

            Partition.Initialize();
        }
示例#14
0
        public void Setup(IAgentData interfacer)
        {
            gameObject.SetActive(true);
            LoadComponents();

            GameObject.DontDestroyOnLoad(gameObject);

            setupAbilitys.FastClear();

            MyAgentCode  = interfacer.Name;
            Data         = interfacer;
            SpawnVersion = 1;
            CheckCasting = true;

            Influencer = new LSInfluencer();
            if (_visualCenter == null)
            {
                _visualCenter = CachedTransform;
            }

            if (Animator.IsNotNull())
            {
                Animator.Setup();
            }

            Body = UnityBody.InternalBody;
            Body.Setup(this);
            abilityManager.Setup(this);


            Influencer.Setup(this);



            SelectionRadiusSquared = SelectionRadius * SelectionRadius;

            this.RegisterLockstep();

            Setuped = true;
        }
示例#15
0
        public static void Initialize()
        {
            PressedInputs     = 0;
            PressedDownInputs = 0;
            PressedUpInputs   = 0;
            InputCount        = 0;
            inputPairs.FastClear();

            AddInput(InputCode.Q, KeyCode.Q);
            AddInput(InputCode.W, KeyCode.W);
            AddInput(InputCode.E, KeyCode.E);
            AddInput(InputCode.R, KeyCode.R);
            AddInput(InputCode.A, KeyCode.A);
            AddInput(InputCode.S, KeyCode.S);
            AddInput(InputCode.D, KeyCode.D);
            AddInput(InputCode.F, KeyCode.F);
            AddInput(InputCode.Z, KeyCode.Z);
            AddInput(InputCode.X, KeyCode.X);
            AddInput(InputCode.C, KeyCode.C);
            AddInput(InputCode.V, KeyCode.V);
            AddInput(InputCode.M, KeyCode.M);
        }
        public static void Initialize()
        {
            PeakCount = 0;

            CachedIDs.FastClear();
            SimObjectExists.Clear();
            //CollisionPairs.Clear ();
            //SimObjects.Clear ();
            CollisionPair.CurrentCollisionPair = null;

            PeakCount        = 0;
            AssimilatedCount = 0;

            FastCollisionPairs.FastClear();

            Partition.Initialize();

            if (SettingsChanged)
            {
                SettingsChanged = false;
            }
        }
示例#17
0
        private static void DestinationReached()
        {
            outputPath.FastClear();
            TracePath.FastClear();

            currentNode = endNode;

            StartNodeIndex = startNode.gridIndex;
            while (currentNode.gridIndex != StartNodeIndex)
            {
                TracePath.Add(currentNode);
                oldNode     = currentNode;
                currentNode = currentNode.parent;
            }
            #if true
            oldX        = 0;
            oldY        = 0;
            currentNode = TracePath[TracePath.Count - 1];
            for (i = TracePath.Count - 2; i >= 0; i--)
            {
                oldNode     = currentNode;
                currentNode = TracePath.innerArray [i];
                newX        = currentNode.gridX - oldNode.gridX;
                newY        = currentNode.gridY - oldNode.gridY;

                #if true
                if (newX != oldX || newY != oldY)
                {
                    outputPath.Add(oldNode);
                    oldX = newX;
                    oldY = newY;
                }
                #else
                outputPath.Add(currentNode);
                #endif
            }
            #endif
        }
示例#18
0
        /// <summary>
        /// Registers an object and returns a ticket to access variable info about the object.
        /// Note: Ticket may vary on multiple clients and sessions.
        /// </summary>
        /// <param name="lockstepObject">Lockstep object.</param>
        public static int Register(object lockstepObject)
        {
            Type type = lockstepObject.GetType();

            string[]            propertyNames;
            LSVariableContainer container;

            if (!CachedLockstepPropertyNames.TryGetValue(type, out propertyNames))
            {
                bufferPropertyNames.FastClear();
                container = new LSVariableContainer(GetVariables(lockstepObject, type));
                foreach (LSVariable info in container.Variables)
                {
                    bufferPropertyNames.Add(info.Info.Name);
                }
                CachedLockstepPropertyNames.Add(type, bufferPropertyNames.ToArray());
            }
            else
            {
                container = new LSVariableContainer(GetVariables(lockstepObject, type, propertyNames));
            }
            return(Containers.Add(container));
        }
示例#19
0
        public byte[] GetBytes () {
            this.Serialize();

            bufferBites.FastClear();
            //Serialize header
            int headerLength = Header.Length;
            int headerArraySize = (headerLength - 1) / 8 + 1;

            bufferBites.Add((byte)headerArraySize);
            byte[] headerBytes = new byte[headerArraySize];

            Header.CopyTo(headerBytes, 0);

            bufferBites.AddRange(headerBytes);

            //Serializing the good stuff
            for (int i = 0; i < Header.Length; i++) {
                if (Header.Get(i)) {
                    bufferBites.Add(Data[i]);
                }
            }
            return bufferBites.ToArray();
        }
示例#20
0
        public void Serialize(FastEnumerable <LSAgent> selectedAgents)
        {
            Data.FastClear();
            selectedAgentLocalIDs.FastClear();
            bufferAgents.FastClear();
            selectedAgents.Enumerate(bufferAgents);
            ushort highestID = 0;

            for (int i = 0; i < bufferAgents.Count; i++)
            {
                ushort id = bufferAgents[i].LocalID;
                if (id > highestID)
                {
                    highestID = id;
                }
            }
            int headerLength = (highestID + 1 - 1) / 8 + 1;

            Header = new BitArray(headerLength, false);
            for (int i = 0; i < bufferAgents.Count; i++)
            {
                SerializeAgent(bufferAgents[i]);
            }
        }
 public void Reset()
 {
     ContainedDynamicObjects.FastClear();
     ContainedImmovableObjects.FastClear();
 }
示例#22
0
        /// <summary>
        /// Finds a path and outputs it to <c>OutputPath</c>. Note: OutputPath is unpredictably changed.
        /// </summary>
        /// <returns>
        /// Returns <c>true</c> if path was found and necessary, <c>false</c> if path to End is impossible or not found.
        /// </returns>
        /// <param name="startNode">Start node.</param>
        /// <param name="endNode">End node.</param>
        /// <param name="OutputPath">Return path.</param>
        public static bool FindPath(GridNode startNode, GridNode endNode, FastList <GridNode> OutputPath)
        {
            #region Broadphase and Preperation
            if (endNode.Unwalkable)
            {
                return(false);
            }

            if (startNode.Unwalkable)
            {
                return(false);
            }

            if (true)
            {
                #region Obstruction Test
                //Tests if there is a direct path. If there is, no need to run AStar.
                x0 = startNode.gridX;
                y0 = startNode.gridY;
                x1 = endNode.gridX;
                y1 = endNode.gridY;
                if (y1 > y0)
                {
                    compare1 = y1 - y0;
                }
                else
                {
                    compare1 = y0 - y1;
                }
                if (x1 > x0)
                {
                    compare2 = x1 - x0;
                }
                else
                {
                    compare2 = x0 - x1;
                }
                steep = compare1 > compare2;
                if (steep)
                {
                    t  = x0;                    // swap x0 and y0
                    x0 = y0;
                    y0 = t;
                    t  = x1;                    // swap x1 and y1
                    x1 = y1;
                    y1 = t;
                }
                if (x0 > x1)
                {
                    t  = x0;                    // swap x0 and x1
                    x0 = x1;
                    x1 = t;
                    t  = y0;                    // swap y0 and y1
                    y0 = y1;
                    y1 = t;
                }
                dx = x1 - x0;

                dy = (y1 - y0);
                if (dy < 0)
                {
                    dy = -dy;
                }

                error = dx / 2;
                ystep = (y0 < y1) ? 1 : -1;
                y     = y0;
                for (x = x0; x <= x1; x++)
                {
                    retX = (steep ? y : x);
                    retY = (steep ? x : y);

                    if (GridManager.Grid [retX * GridManager.NodeCount + retY].Unwalkable)
                    {
                        break;
                    }
                    else if (x == x1)
                    {
                        OutputPath.FastClear();
                        OutputPath.Add(startNode);
                        OutputPath.Add(endNode);
                        return(true);
                    }

                    error = error - dy;
                    if (error < 0)
                    {
                        y     += ystep;
                        error += dx;
                    }
                }
                #endregion
            }


            GridHeap.FastClear();
            GridClosedSet.FastClear();
            #endregion

            #region AStar Algorithm
            GridHeap.Add(startNode);
            GridNode.HeuristicTargetX = endNode.gridX;
            GridNode.HeuristicTargetY = endNode.gridY;
            while (GridHeap.Count > 0)
            {
                currentNode = GridHeap.RemoveFirst();

                GridClosedSet.Add(currentNode);

                if (currentNode.gridIndex == endNode.gridIndex)
                {
                    OutputPath.FastClear();

                    //Retraces the path then outputs it into OutputPath
                    //Also Simplifies the path


                    oldNode     = endNode;
                    currentNode = endNode.parent;

                    oldX = int.MaxValue;
                    oldY = int.MaxValue;

                    StartNodeIndex = startNode.gridIndex;



                    //if (!endNode.Obstructed) OutputPath.Add (endNode);

                    while (oldNode.gridIndex != StartNodeIndex)
                    {
                        newX = currentNode.gridX - oldNode.gridX;
                        newY = currentNode.gridY - oldNode.gridY;
                        if ((newX != oldX || newY != oldY))
                        {
                            OutputPath.Add(oldNode);
                            oldX = newX;
                            oldY = newY;
                        }

                        oldNode     = currentNode;
                        currentNode = currentNode.parent;
                    }


                    OutputPath.Add(startNode);
                    OutputPath.Reverse();
                    return(true);
                }

                for (i = 0; i < 8; i++)
                {
                    neighbor = currentNode.NeighborNodes [i];


                    if (neighbor == null || neighbor.Unwalkable || GridClosedSet.Contains(neighbor))
                    {
                        continue;
                    }

                    newMovementCostToNeighbor = currentNode.gCost + (currentNode.NeighborDiagnal [i] ? 141 : 100);

                    if (!GridHeap.Contains(neighbor))
                    {
                        neighbor.gCost = newMovementCostToNeighbor;

                        //Optimized heuristic calculation
                        neighbor.CalculateHeurustic();
                        neighbor.parent = currentNode;

                        GridHeap.Add(neighbor);
                    }
                    else if (newMovementCostToNeighbor < neighbor.gCost)
                    {
                        neighbor.gCost = newMovementCostToNeighbor;

                        //Optimized heuristic calculation
                        neighbor.CalculateHeurustic();
                        neighbor.parent = currentNode;

                        GridHeap.UpdateItem(neighbor);
                    }
                }
            }
            #endregion
            return(false);
        }
示例#23
0
 public Selection(FastEnumerable<LSAgent> selectedAgents) {
     bufferAgents.FastClear();
     selectedAgents.Enumerate(bufferAgents);
     this.AddAgents(bufferAgents.ToArray());
 }
示例#24
0
        private bool InternalRaycast(Vector2d From, Vector2d To, int ExceptionID)
        {
            _Version++;

            MadeContact = false;
            Hits.FastClear();


            const int StepSize = 1 << Partition.ShiftSize;

            x0 = From.x;
            y0 = From.y;
            x1 = To.x;
            y1 = To.y;
            if (y1 > y0)
            {
                compare1 = y1 - y0;
            }
            else
            {
                compare1 = y0 - y1;
            }
            if (x1 > x0)
            {
                compare2 = x1 - x0;
            }
            else
            {
                compare2 = x0 - x1;
            }
            steep = compare1 > compare2;
            if (steep)
            {
                t  = x0;                // swap x0 and y0
                x0 = y0;
                y0 = t;
                t  = x1;                // swap x1 and y1
                x1 = y1;
                y1 = t;
            }
            if (x0 > x1)
            {
                t  = x0;                // swap x0 and x1
                x0 = x1;
                x1 = t;
                t  = y0;                // swap y0 and y1
                y0 = y1;
                y1 = t;
            }
            dx = x1 - x0;

            dy = (y1 - y0);
            if (dy < 0)
            {
                dy = -dy;
            }

            error = dx / 2;
            ystep = (y0 < y1) ? StepSize : -StepSize;
            y     = y0;

            AxisX = From.x - To.x;
            AxisY = From.y - To.y;
            Mag   = FixedMath.Sqrt((AxisX * AxisX + AxisY * AxisY) >> FixedMath.SHIFT_AMOUNT);
            if (Mag == 0)
            {
                return(false);
            }
            AxisX   = FixedMath.Div(AxisX, Mag);
            AxisY   = FixedMath.Div(AxisY, Mag);
            AxisMin = Vector2d.Dot(AxisX, AxisY, From.x, From.y);
            AxisMax = Vector2d.Dot(AxisX, AxisY, To.x, To.y);
            if (AxisMin > AxisMax)
            {
                SwapValue = AxisMin;
                AxisMin   = AxisMax;
                AxisMax   = SwapValue;
            }
            PerpProj = Vector2d.Dot(-AxisY, AxisX, From.x, From.y);

            XMin = From.x;
            XMax = To.x;
            if (XMin > XMax)
            {
                SwapValue = XMin;
                XMin      = XMax;
                XMax      = SwapValue;
            }
            YMin = From.y;
            YMax = To.y;
            if (YMin > YMax)
            {
                SwapValue = YMin;
                YMin      = YMax;
                YMax      = SwapValue;
            }
            x = x0;
            while (true)
            {
                if (steep)
                {
                    retX = (y - Partition.OffsetX) / StepSize;
                    retY = (x - Partition.OffsetY) / StepSize;
                }
                else
                {
                    retX = (x - Partition.OffsetX) / StepSize;
                    retY = (y - Partition.OffsetY) / StepSize;
                }

                PartitionNode node = Partition.Nodes [retX * Partition.Count + retY];
                if (node.Count > 0)
                {
                    for (i = 0; i < node.Count; i++)
                    {
                        DidHit = false;

                        LSBody body = PhysicsManager.SimObjects [node [i]];
                        if (body.RaycastVersion != _Version && body.ID != ExceptionID)
                        {
                            body.RaycastVersion = _Version;
                            switch (body.Shape)
                            {
                            case ColliderType.Circle:
                                Projection = Vector2d.Dot(AxisX, AxisY, body.Position.x, body.Position.y);
                                TestMin    = Projection - body.Radius;
                                TestMax    = Projection + body.Radius;
                                if (TestMin < AxisMax)
                                {
                                    if (TestMax > AxisMin)
                                    {
                                        Projection = Vector2d.Dot(-AxisY, AxisX, body.Position.x, body.Position.y);
                                        TestMin    = Projection - body.Radius;
                                        TestMax    = Projection + body.Radius;
                                        if (PerpProj < TestMax && PerpProj > TestMin)
                                        {
                                            DidHit = true;
                                        }
                                    }
                                }
                                break;

                            case ColliderType.AABox:
                                if (AxisMin < body.XMax)
                                {
                                    if (AxisMax > body.XMin)
                                    {
                                        if (PerpProj < body.YMax)
                                        {
                                            if (PerpProj > body.YMin)
                                            {
                                                DidHit = true;
                                            }
                                        }
                                    }
                                }
                                break;
                            }
                            if (DidHit)
                            {
                                Hits.Add(body);
                                MadeContact = true;
                                break;
                            }
                        }
                    }
                }

                error = error - dy;
                if (error < 0)
                {
                    y     += ystep;
                    error += dx;
                }

                if (x >= x1)
                {
                    break;
                }
                x += StepSize;
            }
            return(MadeContact);
        }
示例#25
0
        public static void SmoothPath(FastList <GridNode> nodePath, Vector2d End, FastList <Vector2d> outputVectorPath, int unitSize)
        {
            outputVectorPath.FastClear();
            length = nodePath.Count - 1;
            //culling out unneded nodes


            var StartNode = nodePath[0];

            outputVectorPath.Add(StartNode.WorldPos);
            GridNode oldNode = StartNode;
            long     oldX    = 0;
            long     oldY    = 0;
            long     newX    = 0;
            long     newY    = 0;

            for (i = 1; i < length; i++)
            {
                GridNode node = nodePath[i];

                bool important = false;
                if (unitSize <= 1)
                {
                    important = !node.Clearance;
                }
                else if (unitSize <= 3)
                {
                    important = !node.ExtraClearance;
                }
                else
                {
                    important = true;
                }
                //important = true;
                if (important)
                {
                    newX = node.gridX - oldNode.gridX;
                    newY = node.gridY - oldNode.gridY;
                    if (
                        (newX <= 1 && newX >= -1) &&
                        (newY <= 1 && newY >= -1)
                        )
                    {
                        if (newX == oldX && newY == oldY)
                        {
                            if (oldX != 0 || oldY != 0)
                            {
                                outputVectorPath.RemoveAt(outputVectorPath.Count - 1);
                            }
                        }
                        else
                        {
                            oldX = newX;
                            oldY = newY;
                        }
                    }
                    else
                    {
                        oldX = 0;
                        oldY = 0;
                    }
                    outputVectorPath.Add(node.WorldPos);

                    oldNode = node;
                }
            }
            outputVectorPath.Add(End);
        }
示例#26
0
        /// <summary>
        /// Finds a path and outputs it to <c>outputPath</c>. Note: outputPath is unpredictably changed.
        /// </summary>
        /// <returns>
        /// Returns <c>true</c> if path was found and necessary, <c>false</c> if path to End is impossible or not found.
        /// </returns>
        /// <param name="startNode">Start node.</param>
        /// <param name="endNode">End node.</param>
        /// <param name="outputPath">Return path.</param>
        public static bool FindPath(GridNode _startNode, GridNode _endNode, FastList <GridNode> _outputPath, int _unitSize = 1)
        {
            startNode  = _startNode;
            endNode    = _endNode;
            outputPath = _outputPath;
            unitSize   = _unitSize;

            #region Broadphase and Preperation
            if (endNode.Unwalkable)
            {
                return(false);
            }

            if (startNode.Unwalkable)
            {
                return(false);
            }

            outputPath.FastClear();

            if (System.Object.ReferenceEquals(startNode, endNode))
            {
                outputPath.Add(endNode);
                return(true);
            }

            GridHeap.FastClear();
            GridClosedSet.FastClear();
            #endregion

            #region AStar Algorithm
            GridHeap.Add(startNode);
            GridNode.HeuristicTargetX = endNode.gridX;
            GridNode.HeuristicTargetY = endNode.gridY;

            GridNode.PrepareUnpassableCheck(unitSize);             //Prepare Unpassable check optimizations
            while (GridHeap.Count > 0)
            {
                currentNode = GridHeap.RemoveFirst();
#if false
                Gizmos.DrawCube(currentNode.WorldPos.ToVector3(), Vector3.one);
#endif
                GridClosedSet.Add(currentNode);

                if (currentNode.gridIndex == endNode.gridIndex)
                {
                    //Retraces the path then outputs it into outputPath
                    //Also Simplifies the path
                    DestinationReached();
                    return(true);
                }


                /*
                 * for (i = 0; i < 8; i++) {
                 *      neighbor = currentNode.NeighborNodes [i];
                 *      if (CheckNeighborInvalid ()) {
                 *              //continue;
                 *              //microoptimization... continue is more expensive than letting the loop pass at the end
                 *      } else {
                 *              //0-3 = sides, 4-7 = diagonals
                 *              if (i < 4) {
                 *                      newMovementCostToNeighbor = currentNode.gCost + 100;
                 *              } else {
                 *                      if (i == 4) {
                 *                              if (!GridManager.UseDiagonalConnections)
                 *                                      break;
                 *                      }
                 *                      newMovementCostToNeighbor = currentNode.gCost + 141;
                 *              }
                 *
                 *              AnalyzeNode();
                 *      }
                 * }
                 */
                hasInvalidEdge = false;
                for (int i = 0; i < 4; i++)
                {
                    neighbor = currentNode.NeighborNodes[i];
                    if (CheckNeighborInvalid())
                    {
                        hasInvalidEdge = true;
                    }
                    else
                    {
                        newMovementCostToNeighbor = currentNode.gCost + 100;
                        AnalyzeNode();
                    }
                }

                if (hasInvalidEdge)
                {
                    const int maxCornerObstructions = 1;
                    #region inlining diagonals
                    neighbor = currentNode.NeighborNodes[4];
                    if (!CheckNeighborInvalid())
                    {
                        if (GetObstructionCount(0, 1) <= maxCornerObstructions)
                        {
                            newMovementCostToNeighbor = currentNode.gCost + 141;
                            AnalyzeNode();
                        }
                    }

                    neighbor = currentNode.NeighborNodes[5];
                    if (!CheckNeighborInvalid())
                    {
                        if (GetObstructionCount(0, 2) <= maxCornerObstructions)
                        {
                            newMovementCostToNeighbor = currentNode.gCost + 141;
                            AnalyzeNode();
                        }
                    }
                    neighbor = currentNode.NeighborNodes[6];
                    if (!CheckNeighborInvalid())
                    {
                        if (GetObstructionCount(3, 1) <= maxCornerObstructions)
                        {
                            newMovementCostToNeighbor = currentNode.gCost + 141;
                            AnalyzeNode();
                        }
                    }
                    neighbor = currentNode.NeighborNodes[7];
                    if (!CheckNeighborInvalid())
                    {
                        if (GetObstructionCount(3, 2) <= maxCornerObstructions)
                        {
                            newMovementCostToNeighbor = currentNode.gCost + 141;
                            AnalyzeNode();
                        }
                    }
                    #endregion
                }
                else
                {
                    //no need for specific stuff when edges are all valid
                    for (int i = 4; i < 8; i++)
                    {
                        neighbor = currentNode.NeighborNodes[i];
                        if (CheckNeighborInvalid())
                        {
                        }
                        else
                        {
                            newMovementCostToNeighbor = currentNode.gCost + 141;
                            AnalyzeNode();
                        }
                    }
                }
            }
            #endregion
            return(false);
        }
 public static void Initialize()
 {
     Teams.FastClear();
     nextDistribute = 0;
 }
示例#28
0
 /// <summary>
 /// For re-useability
 /// </summary>
 /// <param name="canvas">Canvas.</param>
 public void Initialize(FastList <byte> canvas)
 {
     canvas.FastClear();
     Canvas = canvas;
 }
示例#29
0
 public void Enumerate(FastList <T> output)
 {
     output.FastClear();
     output.AddRange(this);
 }
        public bool Overlaps(FastList <Vector2d> outputIntersectionPoints)
        {
            outputIntersectionPoints.FastClear();
            //Checks if this object overlaps the line formed by p1 and p2
            switch (this.Shape)
            {
            case ColliderType.Circle:
            {
                bool overlaps = false;
                //Check if the circle completely fits between the line
                long projPos = this._position.Dot(cacheAxis.x, cacheAxis.y);
                //Circle withing bounds?
                if (projPos >= axisMin && projPos <= axisMax)
                {
                    long projPerp = this._position.Dot(cacheAxisNormal.x, cacheAxisNormal.y);
                    long perpDif  = (cacheProjPerp - projPerp);
                    long perpDist = perpDif.Abs();
                    if (perpDist <= _radius)
                    {
                        overlaps = true;
                    }
                    if (overlaps)
                    {
                        long sin = (perpDif);
                        long cos = FixedMath.Sqrt(_radius.Mul(_radius) - sin.Mul(sin));
                        if (cos == 0)
                        {
                            outputIntersectionPoints.Add((cacheAxis * projPos) + perpVector);
                        }
                        else
                        {
                            outputIntersectionPoints.Add(cacheAxis * (projPos - cos) + perpVector);
                            outputIntersectionPoints.Add(cacheAxis * (projPos + cos) + perpVector);
                        }
                    }
                }
                else
                {
                    //If not, check distances to points
                    long p1Dist = _position.FastDistance(cacheP1.x, cacheP2.y);
                    if (p1Dist <= this.FastRadius)
                    {
                        outputIntersectionPoints.Add(cacheP1);
                        overlaps = true;
                    }
                    long p2Dist = _position.FastDistance(cacheP2.x, cacheP2.y);
                    if (p2Dist <= this.FastRadius)
                    {
                        outputIntersectionPoints.Add(cacheP2);
                        overlaps = true;
                    }
                }
                return(overlaps);
            }
            break;

            case ColliderType.AABox:
            {
            }
            break;

            case ColliderType.Polygon:
            {
                bool intersected = false;


                for (int i = 0; i < this.Vertices.Length; i++)
                {
                    int      edgeIndex = i;
                    Vector2d pivot     = this.RealPoints [edgeIndex];
                    Vector2d edge      = this.Edges [edgeIndex];
                    long     proj1     = 0;
                    int      nextIndex = edgeIndex + 1 < this.RealPoints.Length ? edgeIndex + 1 : 0;
                    Vector2d nextPoint = RealPoints [nextIndex];
                    long     proj2     = (nextPoint - pivot).Dot(edge);

                    long min;
                    long max;
                    if (proj1 < proj2)
                    {
                        min = proj1;
                        max = proj2;
                    }
                    else
                    {
                        min = proj2;
                        max = proj1;
                    }

                    long lineProj1 = (cacheP1 - pivot).Dot(edge);
                    long lineProj2 = (cacheP2 - pivot).Dot(edge);

                    long lineMin;
                    long lineMax;
                    if (lineProj1 < lineProj2)
                    {
                        lineMin = lineProj1;
                        lineMax = lineProj2;
                    }
                    else
                    {
                        lineMin = lineProj2;
                        lineMax = lineProj1;
                    }
                    if (CollisionPair.CheckOverlap(min, max, lineMin, lineMax))
                    {
                        Vector2d edgeNorm      = this.EdgeNorms [edgeIndex];
                        long     normProj      = 0;
                        long     normLineProj1 = (cacheP1 - pivot).Dot(edgeNorm);
                        long     normLineProj2 = (cacheP2 - pivot).Dot(edgeNorm);

                        long normLineMin;
                        long normLineMax;

                        if (normLineProj1 < normLineProj2)
                        {
                            normLineMin = normLineProj1;
                            normLineMax = normLineProj2;
                        }
                        else
                        {
                            normLineMin = normLineProj2;
                            normLineMax = normLineProj1;
                        }

                        if (normProj >= normLineMin && normProj <= normLineMax)
                        {
                            long revProj1 = pivot.Dot(LSBody.cacheAxisNormal);
                            long revProj2 = nextPoint.Dot(cacheAxisNormal);

                            long revMin;
                            long revMax;
                            if (revProj1 < revProj2)
                            {
                                revMin = revProj1;
                                revMax = revProj2;
                            }
                            else
                            {
                                revMin = revProj2;
                                revMax = revProj1;
                            }

                            if (LSBody.cacheProjPerp >= revMin && LSBody.cacheProjPerp <= revMax)
                            {
                                intersected = true;
                                if (LSBody.calculateIntersections)
                                {
                                    long fraction         = normLineProj1.Abs().Div(normLineMax - normLineMin);
                                    long intersectionProj = FixedMath.Lerp(lineProj1, lineProj2, fraction);
                                    outputIntersectionPoints.Add(edge * intersectionProj + pivot);

                                    if (outputIntersectionPoints.Count == 2)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                return(intersected);
            }
            break;
            }
            return(false);
        }