Example #1
0
        public List <Vector3> GetShortestPath(Vector3 from, Vector3 to)
        {
            int startNavUnit = GetIndexFromPos(GetNavUnitPos(from));
            int endNavUnit   = GetIndexFromPos(GetNavUnitPos(to));

            NativeList <int> aStarPath   = new NativeList <int>(Allocator.TempJob);
            FindPathJob      findPathJob = new FindPathJob()
            {
                navGridSizeX    = navGridSizeX,
                navGridSizeY    = navGridSizeY,
                navGridSizeZ    = navGridSizeZ,
                navUnits        = _navUnits,
                neighborOffsets = _neighborOffsets,
                start           = startNavUnit,
                end             = endNavUnit,
                path            = aStarPath,
            };
            JobHandle jobHandle = findPathJob.Schedule();

            jobHandle.Complete();

            List <Vector3> path = new List <Vector3>();

            for (int i = 0; i < aStarPath.Length; i++)
            {
                path.Add(_navUnits[aStarPath[i]].GetRelativeBounds().center);
            }

            aStarPath.Dispose();

            return(path);
        }
Example #2
0
    protected override void OnUpdate()
    {
        if (pathNodeArray.IsCreated == false)
        {
            ObstacleController.instance.initializePathNodeArray(gridWidth, gridHeight);

            //TODO: I don't know if in need to fetch this from the obstacle controller each update because it is a struct and not a reference
            pathNodeArray = ObstacleController.instance.GetPathNodeArray();
        }

        if (nativeInt == null)
        {
            nativeInt = new NativeArray <int>();
        }



        List <FindPathJob>     findPathJobList = new List <FindPathJob>();
        NativeList <JobHandle> jobHandleList   = new NativeList <JobHandle>(Allocator.Temp);



        Entities.ForEach((Entity entity, ref PathfindingParams pathfindingParams) =>
        {
            // NativeArray<PathNode> tmpPathNodeArray = new NativeArray<PathNode>(pathNodeArray, Allocator.TempJob);

            FindPathJob findPathJob = new FindPathJob
            {
                gridSize             = gridSize,
                pathNodeArray        = new NativeArray <OldPathNode>(pathNodeArray, Allocator.TempJob),
                startPosition        = pathfindingParams.startPosition,
                endPosition          = pathfindingParams.endPosition,
                entity               = entity,
                neighbourOffsetArray = neighbourOffsetArray
            };
            findPathJobList.Add(findPathJob);
            jobHandleList.Add(findPathJob.Schedule());

            //tmpPathNodeArray.Dispose();

            PostUpdateCommands.RemoveComponent <PathfindingParams>(entity);
        });

        JobHandle.CompleteAll(jobHandleList);

        foreach (FindPathJob findPathJob in findPathJobList)
        {
            new SetBufferPathJob
            {
                entity        = findPathJob.entity,
                gridSize      = findPathJob.gridSize,
                pathNodeArray = findPathJob.pathNodeArray,
                pathfindingParamsComponentDataFromEntity = GetComponentDataFromEntity <PathfindingParams>(),
                pathFollowComponentDataFromEntity        = GetComponentDataFromEntity <PathFollow>(),
                pathPositionBufferFromEntity             = GetBufferFromEntity <PathPosition>(),
            }.Run();
        }

        //pathNodeArray.Dispose();
    }
Example #3
0
        protected override void OnUpdate()
        {
            var data      = GetSingleton <PathFinderComponent>();
            var resources = GetSingleton <PathFinderSystemStateComponent>();
            var destroyed = GetBufferFromEntity <DestroyedTriangleElement>(true);
            var buffer    = _buffer;
            var queue     = _queue;
            var writer    = queue.AsParallelWriter();

            Entities
            .WithBurst()
            .WithName("GatherAgentsToRecalculate")
            .WithReadOnly(destroyed)
            .ForEach((Entity entity, int nativeThreadIndex, NavmeshAgentComponent navmesh, ref PathQueryComponent query, ref DynamicBuffer <TriangleElement> triangles) =>
            {
                if (query.State == PathQueryState.PathFound)
                {
                    var seq0 = destroyed[navmesh.Navmesh].Reinterpret <int>();
                    var seq1 = triangles.Reinterpret <int>();

                    if (SortedSequencesContainIdenticalElement(seq0, seq1))
                    {
                        query.State = PathQueryState.Invalidated;
                    }
                }

                if ((query.State & data.RecalculateFlags & ~PathQueryState.Inactive) != 0)
                {
                    writer.Enqueue(entity);
                }
            })
            .ScheduleParallel();

            Job
            .WithBurst()
            .WithCode(() =>
            {
                buffer.Clear();
                while (queue.TryDequeue(out var e))
                {
                    buffer.Add(e);
                }
            })
            .Schedule();

            Dependency = new FindPathJob
            {
                Agents            = buffer.AsDeferredJobArray(),
                NavmeshElements   = GetComponentDataFromEntity <NavmeshAgentComponent>(true),
                Navmeshes         = GetComponentDataFromEntity <NavmeshComponent>(true),
                LTWLookup         = GetComponentDataFromEntity <LocalToWorld>(true),
                TranslationLookup = GetComponentDataFromEntity <Translation>(true),
                Queries           = GetComponentDataFromEntity <PathQueryComponent>(),
                Radii             = GetComponentDataFromEntity <RadiusComponent>(true),
                PathSegments      = GetBufferFromEntity <PathSegmentElement>(),
                TriangleIds       = GetBufferFromEntity <TriangleElement>(),
                PathFinder        = resources,
            }
            .Schedule(buffer, 1, Dependency);
        }
Example #4
0
 private void Update()
 {
     if (target != null && Vector3.Distance(targetPos, target.position) > 0.5f)
     {
         NativeList <int2> nativePath = new NativeList <int2>(Allocator.TempJob);
         var findPathJob = new FindPathJob
         {
             endPosition   = PathFindingNodeFromWorldPosition(target.position),
             startPosition = PathFindingNodeFromWorldPosition(transform.position),
             finalPath     = nativePath,
         };
         var findPathHandle = findPathJob.Schedule();
         findPathHandle.Complete();
         pathList = nativePath.ToArray().ToList();
         nativePath.Dispose();
         pathList.Reverse();
     }
     if (pathList != null && pathList.Count > 0)
     {
         int2 pos = PathFindingNodeFromWorldPosition(transform.position);
         if (!pos.Equals(pathList[0]))
         {
             transform.position = Vector3.MoveTowards(transform.position, new Vector3(pathList[0].x + 0.5f, 1, pathList[0].y + 0.5f), speed * Time.deltaTime);
         }
         else
         {
             Debug.Log("YEs");
             pathList.RemoveAt(0);
         }
     }
     targetPos = target.position;
 }
    protected override void OnUpdate()
    {
        int2 gridSize = new int2(PathfindingGridSetup.Instance.pathfindingGrid.GetWidth(), PathfindingGridSetup.Instance.pathfindingGrid.GetHeight());
        // Everytime an entity recieves a pathfinding param, its going to run pathfinding and then
        // remove the pathfinding param
        NativeList <JobHandle> jobHandleList = new NativeList <JobHandle>(Allocator.Temp);

        Entities.ForEach((Entity entity, DynamicBuffer <PathPositionBuffer> pathPositionBuffer, ref PathfindingParams pathfindingParams) =>
        {
            //Debug.Log("Find Path!");
            FindPathJob findPathJob = new FindPathJob
            {
                pathNodeArray = GetPathNodeArray(),
                gridSize      = gridSize,
                startPosition = pathfindingParams.startPosition,
                endPosition   = pathfindingParams.endPosition,
                pathPositionBufferFromEntity      = GetBufferFromEntity <PathPositionBuffer>(),
                pathFollowComponentDataFromEntity = GetComponentDataFromEntity <PathFollowComp>(),
                entity = entity
            };
            jobHandleList.Add(findPathJob.Schedule());
            //findPathJob.Run();

            // remove to make sure pathfinding only runs once per entity
            PostUpdateCommands.RemoveComponent <PathfindingParams>(entity);
        });
        JobHandle.CompleteAll(jobHandleList);
        jobHandleList.Dispose();
    }
Example #6
0
    private void Start()
    {
        FunctionPeriodic.Create(() =>
        {
            float startTime = Time.realtimeSinceStartup;

            if (!useJobs)
            {
                for (int i = 0; i < 5; i++)
                {
                    FindPath(new int2(0, 0), new int2(19, 19));
                }
            }
            else
            {
                int findPathJobCount = 5;
                NativeArray <JobHandle> jobHandleArray = new NativeArray <JobHandle>(findPathJobCount, Allocator.Temp);

                for (int i = 0; i < findPathJobCount; i++)
                {
                    FindPathJob findPathJob = new FindPathJob
                    {
                        startPosition = new int2(0, 0),
                        endPosition   = new int2(19, 19)
                    };
                    jobHandleArray[i] = findPathJob.Schedule();
                }

                JobHandle.CompleteAll(jobHandleArray);
                jobHandleArray.Dispose();
            }

            Debug.Log("Time: " + ((Time.realtimeSinceStartup - startTime) * 1000f));
        }, 1f);
    }
Example #7
0
 protected override void OnUpdate()
 {
     Entities.ForEach((Entity entity, ref PathFindingParamsComponent pathFindingParamsComponent) => {
         Debug.Log("FindPath!");
         FindPathJob findPathJob = new FindPathJob {
             startPosition = pathFindingParamsComponent.startPosition,
             endPosition   = pathFindingParamsComponent.endPosition,
         };
         findPathJob.Run();
         PostUpdateCommands.RemoveComponent <PathFindingParamsComponent>(entity);
     });
 }
Example #8
0
    protected override void OnUpdate()
    {
        if (SceneManager.GetActiveScene().name == "GameScene")
        {
            if (!isAwake)
            {
                gridWidth  = PathfindingGridSetup.Instance.pathfindingGrid.GetWidth();
                gridHeight = PathfindingGridSetup.Instance.pathfindingGrid.GetHeight();
                gridSize   = new int2(gridWidth, gridHeight);
            }

            List <FindPathJob>     findPathJobList = new List <FindPathJob>();
            NativeList <JobHandle> jobHandleList   = new NativeList <JobHandle>(Allocator.Temp);

            NativeArray <PathNode> pathNodeArray = GetPathNodeArray();

            Entities.ForEach((Entity entity, ref DestinationComponent destination) =>
            {
                NativeArray <PathNode> tmpPathNodeArray = new NativeArray <PathNode>(pathNodeArray, Allocator.TempJob);

                FindPathJob findPathJob = new FindPathJob
                {
                    gridSize      = gridSize,
                    pathNodeArray = tmpPathNodeArray,
                    startPosition = destination.startPosition,
                    endPosition   = destination.endPosition,
                    entity        = entity,
                };
                findPathJobList.Add(findPathJob);
                jobHandleList.Add(findPathJob.Schedule());
                //Debug.Log("pathfinding system onupdate)");
                PostUpdateCommands.RemoveComponent <DestinationComponent>(entity);
            });

            JobHandle.CompleteAll(jobHandleList);

            foreach (FindPathJob findPathJob in findPathJobList)
            {
                new SetBufferPathJob
                {
                    entity        = findPathJob.entity,
                    gridSize      = findPathJob.gridSize,
                    pathNodeArray = findPathJob.pathNodeArray,
                    destinationComponentDataFromEntity = GetComponentDataFromEntity <DestinationComponent>(),
                    pathFollowComponentDataFromEntity  = GetComponentDataFromEntity <PathFollow>(),
                    pathPositionBufferFromEntity       = GetBufferFromEntity <PathPosition>(),
                }.Run();
            }

            pathNodeArray.Dispose();
        }
    }
Example #9
0
        protected override void OnUpdate()
        {
            // 地图大小
            int  gridWidth  = PathfindingManager.Instance.navMap.xCount;
            int  gridHeight = PathfindingManager.Instance.navMap.yCount;
            int2 gridSize   = new int2(gridWidth, gridHeight);

            // 存放Job数据
            List <FindPathJob> findPathJobList = new List <FindPathJob>();
            // 存放Job句柄,用于下面的CompleteAll
            NativeList <JobHandle> jobHandleList = new NativeList <JobHandle>(Allocator.Temp);
            // 存放地图数据
            NativeArray <PathNode> pathNodeArray = GetPathNodeArray();

            Entities.ForEach((Entity entity, ref PathfindingParams pathfindingParams) =>
            {
                // 复制一份,因为每个寻路都会用到,并改变其值
                NativeArray <PathNode> tmpPathNodeArray = new NativeArray <PathNode>(pathNodeArray, Allocator.TempJob);
                FindPathJob findPathJob = new FindPathJob
                {
                    gridSize      = gridSize,
                    pathNodeArray = tmpPathNodeArray,
                    startPosition = pathfindingParams.startPosition,
                    endPosition   = pathfindingParams.endPosition,
                    entity        = entity,
                };
                findPathJobList.Add(findPathJob);
                jobHandleList.Add(findPathJob.Schedule());
                // 移除寻路参数
                PostUpdateCommands.RemoveComponent <PathfindingParams>(entity);
            });
            // 完成所有寻路Job
            JobHandle.CompleteAll(jobHandleList);

            // 开启写入寻路数据的Job
            foreach (FindPathJob findPathJob in findPathJobList)
            {
                new SetBufferPathJob
                {
                    entity        = findPathJob.entity,
                    gridSize      = findPathJob.gridSize,
                    pathNodeArray = findPathJob.pathNodeArray,
                    pathfindingParamsComponentDataFromEntity = GetComponentDataFromEntity <PathfindingParams>(),
                    pathFollowComponentDataFromEntity        = GetComponentDataFromEntity <PathFollow>(),
                    pathPositionBufferFromEntity             = GetBufferFromEntity <PathPosition>(),
                }.Run();
            }

            // 记得释放非托管内存
            pathNodeArray.Dispose();
        }
Example #10
0
    protected override void OnUpdate()
    {
        Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> dynamicBuffer, ref PathfindingParamsComponent pathfindingParamsComponent) =>
        {
            FindPathJob findPathJob = new FindPathJob {
                startPosition      = pathfindingParamsComponent.startPosition,
                endPosition        = pathfindingParamsComponent.endPosition,
                pathPositionBuffer = dynamicBuffer
            };

            findPathJob.Execute();

            PostUpdateCommands.RemoveComponent <PathfindingParamsComponent>(entity);
        });
    }
Example #11
0
    protected override void OnUpdate()
    {
        int  gridWidth  = PathfindingGridSetup.Instance.pathfindingGrid.GetWidth();
        int  gridHeight = PathfindingGridSetup.Instance.pathfindingGrid.GetHeight();
        int2 gridSize   = new int2(gridWidth, gridHeight);

        List <FindPathJob>     findPathJobList = new List <FindPathJob>();
        NativeList <JobHandle> jobHandleList   = new NativeList <JobHandle>(Allocator.Temp);

        NativeArray <PathNode> pathNodeArray = GetPathNodeArray();

        Entities.ForEach((Entity entity, ref PathfindingParams pathfindingParams) =>
        {
            NativeArray <PathNode> tmpPathNodeArray = new NativeArray <PathNode>(pathNodeArray, Allocator.TempJob);

            FindPathJob findPathJob = new FindPathJob
            {
                gridSize      = gridSize,
                pathNodeArray = tmpPathNodeArray,
                startPosition = pathfindingParams.startPosition,
                endPosition   = pathfindingParams.endPosition,
                entity        = entity,
            };
            findPathJobList.Add(findPathJob);
            jobHandleList.Add(findPathJob.Schedule());

            PostUpdateCommands.RemoveComponent <PathfindingParams>(entity);
        });

        JobHandle.CompleteAll(jobHandleList);

        foreach (FindPathJob findPathJob in findPathJobList)
        {
            new SetBufferPathJob {
                entity        = findPathJob.entity,
                gridSize      = findPathJob.gridSize,
                pathNodeArray = findPathJob.pathNodeArray,
                pathfindingParamsComponentDataFromEntity = GetComponentDataFromEntity <PathfindingParams>(),
                pathFollowComponentDataFromEntity        = GetComponentDataFromEntity <PathFollow>(),
                pathPositionBufferFromEntity             = GetBufferFromEntity <PathPosition>(),
            }.Run();
        }

        pathNodeArray.Dispose();
    }
Example #12
0
    protected override void OnUpdate()
    {
        //Setup grid
        int gridWidth  = AIGrid.Instance.pathfindingGrid.GetWidth();
        int gridHeight = AIGrid.Instance.pathfindingGrid.GetHeight();
        List <FindPathJob>     findPathJobList = new List <FindPathJob>();
        NativeList <JobHandle> jobHandleList   = new NativeList <JobHandle>(Allocator.Temp);

        //For every entity with pathfinding data
        Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuffer, ref PathfindingComponentData pathfindingComponentData) =>
        {
            //Create pathfinding job
            FindPathJob findPathJob = new FindPathJob
            {
                pathNodeArray = GetPathNodeArray(),
                startPosition = pathfindingComponentData.startPosition,
                endPosition   = pathfindingComponentData.endPosition,
                gridSize      = new int2(gridWidth, gridHeight),
                //pathPositionBuffer = pathPositionBuffer,
                entity = entity,
                pathFollowComponentDataFromEntity = GetComponentDataFromEntity <PathFollowComponent>()
            };
            findPathJobList.Add(findPathJob);
            jobHandleList.Add(findPathJob.Schedule());
            PostUpdateCommands.RemoveComponent <PathfindingComponentData>(entity);
        });
        //Complete all jobs
        JobHandle.CompleteAll(jobHandleList);

        //Buffer path job for each entity
        foreach (FindPathJob job in findPathJobList)
        {
            new SetBufferPathJob
            {
                entity        = job.entity,
                gridSize      = job.gridSize,
                pathNodeArray = job.pathNodeArray,
                pathfindingComponentDataFromEntity = GetComponentDataFromEntity <PathfindingComponentData>(),
                pathFollowComponentDataFromEntity  = GetComponentDataFromEntity <PathFollowComponent>(),
                pathPositionBufferFromEntity       = GetBufferFromEntity <PathPosition>(),
            }.Run();
        }
        //Dispose of array
        jobHandleList.Dispose();
    }
    private void Update()
    {
        if (m_target.position == m_player.position)
        {
            return;
        }

        //NativeList<Node>

        FindPathJob findPathJob = new FindPathJob()
        {
            gridData = grid.pathGridData,
            startPos = m_player.position,
            endPos   = m_target.position,
            callback = FindPathJobCallback
        };
        JobHandle handle = findPathJob.Schedule();

        handle.Complete();
    }
    public void TestPathFinding(int findPathConcurrentJobCount)
    {
        float startTime = Time.realtimeSinceStartup;

        NativeArray <JobHandle> jobHandleArray = new NativeArray <JobHandle>(findPathConcurrentJobCount, Allocator.TempJob);

        for (int i = 0; i < findPathConcurrentJobCount; i++)
        {
            FindPathJob findPathJob = new FindPathJob {
                startingPosition = new int2(0, 0),
                endPosition      = new int2(19, 19)
            };
            jobHandleArray[i] = findPathJob.Schedule();
        }

        JobHandle.CompleteAll(jobHandleArray);
        jobHandleArray.Dispose();

        Debug.Log("Time: " + ((Time.realtimeSinceStartup - startTime) * 1000f));
    }
Example #15
0
    protected override void OnUpdate()
    {
        var  ecb        = _ecbSystem.CreateCommandBuffer().AsParallelWriter();
        int  gridWidth  = DefaultNamespace.SetupPathFindingGrid.Instance.Grid.GetWidth();
        int  gridHeight = DefaultNamespace.SetupPathFindingGrid.Instance.Grid.GetHeight();
        int2 gridSize   = new int2(gridWidth, gridHeight);

        var pathNodeArray = GetPathNodeArray();

        _neighbourOffsets = new NativeArray <int2>(8, Allocator.TempJob)
        {
            [0] = new int2(-1, 0),  //left
            [1] = new int2(+1, 0),  //right
            [2] = new int2(0, +1),  //up
            [3] = new int2(0, -1),  //down
            [4] = new int2(-1, -1), //left down
            [5] = new int2(-1, +1), //left up
            [6] = new int2(+1, -1), //right down
            [7] = new int2(+1, +1), //right up
        };

        var entities = _query.ToEntityArrayAsync(Allocator.TempJob, out JobHandle jobhandle);

        Dependency = JobHandle.CombineDependencies(Dependency, jobhandle);
        Dependency = new FindPathJob
        {
            GridSize              = gridSize,
            PathNodeArray         = new NativeArray <PathNode>(pathNodeArray, Allocator.TempJob),
            PathfindingParamsType = GetComponentTypeHandle <PathfindingParams>(),
            PathIndexType         = GetComponentTypeHandle <PathIndex>(),
            PathPositionType      = GetBufferTypeHandle <PathPosition>(),
            CommandBuffer         = ecb,
            EntityType            = GetEntityTypeHandle(),
            NeighbourOffsets      = new NativeArray <int2>(_neighbourOffsets, Allocator.TempJob),
        }.ScheduleParallel(_query, Dependency);

        _ecbSystem.AddJobHandleForProducer(Dependency);
        pathNodeArray.Dispose(Dependency);
        entities.Dispose(Dependency);
        _neighbourOffsets.Dispose(Dependency);
    }
Example #16
0
    private float Test <T>() where T : IOpenList, new()
    {
        float startTime      = Time.realtimeSinceStartup;
        var   jobHandleArray = new NativeArray <JobHandle>(JOB_COUNT, Allocator.TempJob);

        for (int i = 0; i < JOB_COUNT; i++)
        {
            var job = new FindPathJob <T> {
                startPosition = new int2(0, 0),
                endPosition   = new int2(SIZE_DIM - 1, 0),
                gridSize      = new int2(SIZE_DIM, SIZE_DIM)
            };
            jobHandleArray[i] = job.Schedule();
        }
        JobHandle.CompleteAll(jobHandleArray);
        jobHandleArray.Dispose();

        float timing = (Time.realtimeSinceStartup - startTime) * 1000f;

        return(timing);
    }
Example #17
0
        private void Start()
        {
            int findPathJobCount = 5;
            NativeArray <JobHandle> jobHandleArray = new NativeArray <JobHandle>(findPathJobCount, Allocator.TempJob);

            for (int i = 0; i < findPathJobCount; i++)
            {
                FindPathJob findPathJob = new FindPathJob
                {
                    GridSize      = Info.Map.Size,
                    GridWidth     = Info.Map.Width,
                    StartPosition = new int2(0, 0),
                    EndPosition   = new int2(19, 19),
                    Nodes         = GetNodes(),
                };

                jobHandleArray[i] = findPathJob.Schedule();
            }

            JobHandle.CompleteAll(jobHandleArray);
            jobHandleArray.Dispose();
        }
Example #18
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (m_array.IsCreated)
        {
            m_array.Dispose();
        }
        if (pathOutput.IsCreated)
        {
            pathOutput.Dispose();
        }
        if (currentSelectedEntity.IsCreated)
        {
            currentSelectedEntity.Dispose();
        }

        EntityQuery m_GroupCalculateMove = GetEntityQuery(ComponentType.ReadOnly <CalculateMove>());

        if (m_GroupCalculateMove.CalculateEntityCount() > 0 && m_GroupCalculateMove.CalculateEntityCount() < 2)
        {
            //GetCalculate Move Entity
            m_array = m_GroupCalculateMove.ToComponentDataArray <CalculateMove>(Allocator.TempJob);

            EntityQuery          e_GroupMap = GetEntityQuery(typeof(MapEntityBuffer));
            NativeArray <Entity> e_array    = e_GroupMap.ToEntityArray(Allocator.TempJob);

            DynamicBuffer <Entity> mapEntityBuffers = EntityManager.GetBuffer <MapEntityBuffer>(e_array[0]).Reinterpret <Entity>();
            NativeArray <PathNode> pathNodeArray    = new NativeArray <PathNode>(mapEntityBuffers.Length, Allocator.TempJob);

            // send the end position and startposition with the calculatemove tag
            PopulatePathNodeArray populatePathNodeArrayJob = new PopulatePathNodeArray
            {
                endPosition = m_array[0].Destination,
                lookup      = GetComponentDataFromEntity <Tile>(true),
                mapArray    = mapEntityBuffers.ToNativeArray(Allocator.TempJob),
                nodeArray   = pathNodeArray
            };

            JobHandle populatePathArrayHandle = populatePathNodeArrayJob.Schedule(mapEntityBuffers.Length, 32);
            //inputDeps = populatePathArrayHandle;
            // calculate the path and add the MovePath component the the entity


            populatePathArrayHandle.Complete();

            pathOutput = new NativeList <int2>(Allocator.TempJob);

            FindPathJob findPathJob = new FindPathJob
            {
                endPosition   = m_array[0].Destination,
                startPosition = m_array[0].StartPosition,
                gridSize      = new int2(TileHandler.instance.width, TileHandler.instance.height),
                pathNodeArray = pathNodeArray,
                path          = pathOutput
            };

            JobHandle findPathJobHandle = findPathJob.Schedule(populatePathArrayHandle);
            //inputDeps = JobHandle.CombineDependencies(inputDeps, populatePathArrayHandle);
            findPathJobHandle.Complete();

            if (pathOutput.Length >= 1)
            {
                //remove the CalculateMove component from the entity - create a foreach job with the unitselected and calculate move components
                currentSelectedEntity = new NativeArray <Entity>(1, Allocator.TempJob);
                QueueMoveEntity queueMoveEntity = new QueueMoveEntity
                {
                    currentEntity     = currentSelectedEntity,
                    calculateMoveType = typeof(CalculateMove),
                    commandBuffer     = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
                    pathLength        = pathOutput.Length
                };

                JobHandle queueMoveEntityHandle = queueMoveEntity.Schedule(this, JobHandle.CombineDependencies(findPathJobHandle, inputDeps));
                inputDeps = JobHandle.CombineDependencies(inputDeps, queueMoveEntityHandle);

                queueMoveEntityHandle.Complete();

                if (!currentSelectedEntity[0].Equals(Entity.Null))
                {
                    UpdateBuffer updateBuffer = new UpdateBuffer
                    {
                        path   = pathOutput.AsArray(),
                        entity = currentSelectedEntity[0],
                        lookup = GetBufferFromEntity <PathBuffer>(false)
                    };
                    inputDeps = updateBuffer.Schedule(inputDeps);
                }
            }
            else
            {
                RemoveComponent removeComponent = new RemoveComponent
                {
                    commandBuffer       = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
                    typeOfCalculateMove = typeof(CalculateMove)
                };
                inputDeps = removeComponent.Schedule(this, inputDeps);
            }
            e_array.Dispose();
        }

        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(inputDeps);



        return(inputDeps);
    }
    protected override void OnUpdate()
    {
        bool jobRan = false;

        SetupDebugging();

        entityQuery = GetEntityQuery(typeof(FormationPathFindingState));

        CollectEntitiesWithNewTargetJob collectJob = new CollectEntitiesWithNewTargetJob
        {
            entityQueue                = entityQueue,
            startPositionQueue         = startPositionQueue,
            endPositionQueue           = endPositionQueue,
            archetypeFormationPosition = GetArchetypeChunkComponentType <FormationPosition>(),
            archetypePathfindingState  = GetArchetypeChunkComponentType <FormationPathFindingState>(),
            archetypeTargetPosition    = GetArchetypeChunkComponentType <FormationTargetPosition>(),
            entityType = GetArchetypeChunkEntityType(),
        };

        collectJob.Run(entityQuery);

        if (entityQueue.Count > 0)
        {
            jobRan = true;
            int numJobs = FillEntityLists();

            FindPathJob job = new FindPathJob
            {
                // GRID DATA
                heuristicBias    = HEURISTIC_BIAS,
                graphCellLength  = graph.numCellsAcross,
                graphCellSize    = graph.cellSize,
                graphClusterSize = graph.clusterSize,
                graphNumClusters = graph.numClustersAcross,
                // CLUSTER
                graphClusterEdgesLists = graph.clusterEdges,
                graphClustersDense     = graph.clustersDense,
                graphIntraEdges        = graph.intraEdges,
                graphInterEdges        = graph.interEdges,
                // EDGE
                graphEdgeNeighbourList = graph.edgeNeighbourKeys,
                graphEdgePathList      = graph.pathKeysPerEdge,
                graphEdgePaths         = graph.edgePaths,
                graphEdgePathPositions = graph.edgePathNodePositions,
                graphEdgeNeighbours    = graph.edgeNeighbours,
                // NODE
                graphNodeNeighbourKeys = graph.nodeNeighbourKeys,
                graphNodeNeighbours    = graph.nodeNeighbours,
                graphNodeToEdge        = graph.nodeToEdge,
                graphNodePositions     = graph.nodePositions,
                graphNodeWalkables     = graph.nodeWalkables,
                // READ ENTITY DATA
                entities                    = jobEntities.AsArray(),
                startWorldPositions         = jobStartPositions.AsArray(),
                endWorldPositions           = jobEndPositions.AsArray(),
                targetRotationComponentData = GetComponentDataFromEntity <FormationTargetRotation>(true),
                // WRITE ENTITY DATA
                pathfindingStateComponentData = GetComponentDataFromEntity <FormationPathFindingState>(false),
                pathIndexComponentData        = GetComponentDataFromEntity <PathIndex>(false),
                pathPositionBufferEntity      = GetBufferFromEntity <PathPosition>(false),
            };
            jobHandle  = job.Schedule(numJobs, JOB_BATCH_SIZE, Dependency);
            Dependency = jobHandle;

            #region DEBUGGING

            sw.Stop();

            if (showTime && jobRan)
            {
                UnityEngine.Debug.Log(sw.Elapsed);
            }
            if (showMarkers)
            {
                DebugDrawMarkers();
            }

            #endregion
        }
    }
    protected override void OnUpdate()
    {
        sw.Reset();
        sw.Start();

        bool showTime = false;

        jobEntities.Clear();
        jobStartPositions.Clear();
        jobEndPositions.Clear();

        Entities.ForEach((Entity entity, ref PathFindingOrders pathFindingOrders, ref Translation translation) =>
        {
            entityQueue.Enqueue(entity);
            startPositionQueue.Enqueue(new float2(translation.Value.x, translation.Value.z));
            endPositionQueue.Enqueue(pathFindingOrders.targetPosition);

            PostUpdateCommands.RemoveComponent <PathFindingOrders>(entity);
        });

        int numEntitiesWaiting = entityQueue.Count;

        if (numEntitiesWaiting > 0)
        {
            int numJobs = MAX_JOBS_PER_FRAME;
            if (numEntitiesWaiting < MAX_JOBS_PER_FRAME)
            {
                numJobs = numEntitiesWaiting;
            }

            showTime = true;

            jobEntities.Clear();
            jobStartPositions.Clear();
            jobEndPositions.Clear();

            for (int i = 0; i < numJobs; i++)
            {
                jobEntities.Add(entityQueue.Dequeue());
                jobStartPositions.Add(startPositionQueue.Dequeue());
                jobEndPositions.Add(endPositionQueue.Dequeue());
            }

            FindPathJob job = new FindPathJob
            {
                // GRID DATA
                neighbourOffsetArray = graph.neighbourOffsetArray,
                heuristicBias        = HEURISTIC_BIAS,
                graphCellLength      = graph.numCellsAcross,
                graphCellSize        = graph.cellSize,
                graphClusterLength   = graph.clusterSize,
                graphNumClusters     = graph.numClustersAcross,
                // CLUSTER
                graphClusterEdgesLists = graph.clusterEdges,
                graphClustersDense     = graph.clustersDense,
                graphIntraEdges        = graph.intraEdges,
                graphInterEdges        = graph.interEdges,
                // EDGE
                graphEdgeNeighbourList = graph.edgeNeighbourKeys,
                graphEdgePathList      = graph.pathKeysPerEdge,
                graphEdgePaths         = graph.edgePaths,
                graphEdgePathPositions = graph.edgePathNodePositions,
                graphEdgeNeighbours    = graph.edgeNeighbours,
                // NODE
                graphNodeToEdge    = graph.nodeToEdge,
                graphNodePositions = graph.nodePositions,
                graphNodeWalkables = graph.nodeWalkables,
                // ENTITY DATA
                entities            = jobEntities.AsArray(),
                startWorldPositions = jobStartPositions.AsArray(),
                endWorldPositions   = jobEndPositions.AsArray(),
                // WRITABLE ENTITY DATA
                pathPositionBuffer     = GetBufferFromEntity <PathPosition>(),
                pathIndexComponentData = GetComponentDataFromEntity <PathIndex>()
            };

            JobHandle jobHandle = job.Schedule(numJobs, JOB_BATCH_SIZE);
            jobHandle.Complete();

            sw.Stop();
            if (showTime)
            {
                UnityEngine.Debug.Log(sw.Elapsed);
            }

            Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuffer) =>
            {
                for (int i = 0; i < pathPositionBuffer.Length; i++)
                {
                    Vector3 position = new Vector3(
                        pathPositionBuffer[i].position.x,
                        3,
                        pathPositionBuffer[i].position.y);

                    Object.Instantiate(marker, position, quaternion.identity);
                }
            });
        }
    }
Example #21
0
    protected override void OnUpdate()
    {
        var gridSize = new int2(PathFindingSetup.Instance.pathfindingGrid.GetWidth(),
                                PathFindingSetup.Instance.pathfindingGrid.GetHeight());


        var pathFindingJobs = new List <FindPathJob>();
        var jobHandlerArray = new NativeList <JobHandle>(Allocator.Temp);

        // var pathNodeAryList = new NativeList<NativeArray<PathNode>>(Allocator.Temp);
        // var pathNodeAry = GetPathNodeArray();
        Entities.ForEach((Entity entity, PathFindingParam pathFindingParam) =>
        {
            // var buff = EntityManager.GetBuffer<PathPosition>(entity);
            var pathNodeAry = GetPathNodeArray();

            var pathFindingJob = new FindPathJob
            {
                gridSize      = gridSize,
                pathNodeArray = pathNodeAry,
                startPos      = pathFindingParam.startPos,
                endPos        = pathFindingParam.endPos,
                // pathPositionBuff = buff,
                // bufferFromEntity = GetBufferFromEntity<PathPosition>(),
                entity = entity,
                // pathFollowDataFromEntity = GetComponentDataFromEntity<PathFollow>(),
            };
            pathFindingJobs.Add(pathFindingJob);


            // EntityManager.AddComponentData(entity, new PathComponent());
            // pathFindingJob.Run();
            jobHandlerArray.Add(pathFindingJob.Schedule());

            PostUpdateCommands.RemoveComponent <PathFindingParam>(entity);
        });

        JobHandle.CompleteAll(jobHandlerArray);

        for (var i = 0; i < pathFindingJobs.Count; i++)
        {
            var findJob = pathFindingJobs[i];
            var entity  = findJob.entity;
            var pathFollowComponentDataFromEntity = GetComponentDataFromEntity <PathFollow>();
            var endNodeIndex       = CalculateIndex(findJob.endPos.x, findJob.endPos.y, gridSize.x);
            var pathPositionBuffer = GetBufferFromEntity <PathPosition>()[entity];
            pathPositionBuffer.Clear();
            PathNode endNode = findJob.pathNodeArray[endNodeIndex];
            if (endNode.cameFromNodeIndex == -1)
            {
                // Didn't find a path!
                //Debug.Log("Didn't find a path!");
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    index = -2
                };
            }
            else
            {
                // Found a path
                CalculatePath(findJob.pathNodeArray, endNode, pathPositionBuffer);

                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    index = pathPositionBuffer.Length - 1
                };
            }

            findJob.pathNodeArray.Dispose();
        }
        jobHandlerArray.Dispose();
    }
Example #22
0
    protected override JobHandle OnUpdate(JobHandle jobHandle)
    {
        if (!initialized)
        {
            initializePersistentArrays(numberWorkerThreads, gridParams);
            initialized = true;
        }

        //QuadTree.ClearAndBulkInsert(obstacleArray);

        //NativeList<ObstacleStruct> queryResult = new NativeList<ObstacleStruct>(Allocator.Temp);

        //QuadTree.RangeQuery(new NativeQuadTree.AABB2D(new float2(500, 500), new float2(1000, 1000)), queryResult);

        //Debug.Log(queryResult);



        EntityCommandBuffer concurrentCommandBuffer = entityCommandBufferSystem.CreateCommandBuffer();

        EntityQuery entityQuery = GetEntityQuery(ComponentType.ReadOnly <PathfindingParams>());

        NativeArray <PathfindingParams> pathFindingArray = entityQuery.ToComponentDataArray <PathfindingParams>(Allocator.TempJob);
        NativeArray <Entity>            entityArray      = entityQuery.ToEntityArray(Allocator.TempJob);



        NativeArray <JobHandle> jobHandles = new NativeArray <JobHandle>(jobCollections.Count, Allocator.TempJob);

        for (int index = 0; index < jobCollections.Count; index++)
        {
            jobHandles[index] = jobHandle;
        }

        for (int r = 0; r < entityArray.Length; r++)
        {
            int               index             = r % jobCollections.Count;
            jobCollection     data              = jobCollections[index];
            PathfindingParams pathfindingParams = pathFindingArray[r];

            FindPathJob findPathJob = new FindPathJob
            {
                DimX            = gridParams.x,
                DimY            = gridParams.y,
                Neighbours      = neighbourOffsetArray,
                startPosition   = pathfindingParams.startPosition,
                endPosition     = pathfindingParams.endPosition,
                itterationLimit = itterationLimit,
                Grid            = ObstacleController.instance.getNativeMap(),
                CostSoFar       = data.CostSoFar,
                CameFrom        = data.CameFrom,
                entity          = entityArray[r],
                OpenSet         = data.OpenSet
            };

            JobHandle findPathHandle = findPathJob.Schedule(jobHandles[index]);



            ResetJob resetJob = new ResetJob
            {
                CostSoFar = data.CostSoFar,
                OpenSet   = data.OpenSet,
                CameFrom  = data.CameFrom,
                DimX      = gridParams.x,
                entity    = entityArray[r],
                pathFound = data.foundPath,
                pathfindingParamsComponentDataFromEntity = GetComponentDataFromEntity <PathfindingParams>(),
                pathFollowComponentDataFromEntity        = GetComponentDataFromEntity <PathFollow>(),
                pathPositionBufferFromEntity             = GetBufferFromEntity <PathPosition>(),
                startPosition = pathfindingParams.startPosition,
                endPosition   = pathfindingParams.endPosition,
            };

            jobHandles[index] = resetJob.Schedule(findPathHandle);
            //PostUpdateCommands.RemoveComponent<PathfindingParams>(entity);
            concurrentCommandBuffer.RemoveComponent <PathfindingParams>(entityArray[r]);
        }

        jobHandle = JobHandle.CombineDependencies(jobHandles);
        entityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

        entityArray.Dispose();
        pathFindingArray.Dispose();

        jobHandles.Dispose();


        return(jobHandle);
    }