コード例 #1
0
    public override void OnSceneGUI(NavGraph target)
    {
        //NavMeshGraph graph = target as NavMeshGraph;

        /*if (meshRenderer == null) {
            Debug.Log ("IsNull");
            meshRenderer = new GameObject ("NavmeshRenderer");
            meshRenderer.hideFlags = HideFlags.HideAndDontSave;

            Renderer renderer = meshRenderer.AddComponent (typeof(MeshRenderer)) as Renderer;
            MeshFilter filter = meshRenderer.AddComponent (typeof(MeshFilter)) as MeshFilter;

            Mesh mesh = new Mesh ();
            mesh.vertices = graph.vertices;
            mesh.triangles = graph.triangles;

            mesh.RecalculateBounds ();
            mesh.RecalculateNormals ();

            filter.mesh = mesh;

            renderer.material = new Material (Shader.Find ("Transparent/Diffuse"));
            renderer.material.color = AstarColor.MeshColor;
        } else {
            Debug.Log ("Not Null "+meshRenderer.renderer.enabled+" "+meshRenderer.hideFlags);
            //meshRenderer.transform.position = new Vector3 (0,5,0);//meshRenderer.transform.position+Vector3.up*0.5F;
            meshRenderer.active = false;
            meshRenderer.active = true;

        }*/

        //DrawAALine (Vector3.zero,Vector3.one*20);
    }
コード例 #2
0
    //public GameObject meshRenderer;
    public override void OnInspectorGUI(NavGraph target)
    {
        NavMeshGraph graph = target as NavMeshGraph;
        /*
        #if UNITY_3_3
        graph.sourceMesh = EditorGUILayout.ObjectField ("Source Mesh",graph.sourceMesh,typeof(Mesh)) as Mesh;
        #else
        graph.sourceMesh = EditorGUILayout.ObjectField ("Source Mesh",graph.sourceMesh,typeof(Mesh), true) as Mesh;
        #endif
        */
        graph.sourceMesh = ObjectField ("Source Mesh", graph.sourceMesh, typeof(Mesh), false) as Mesh;

        EditorGUIUtility.LookLikeControls ();
        EditorGUILayoutx.BeginIndent ();
        graph.offset = EditorGUILayout.Vector3Field ("Offset",graph.offset);
        EditorGUILayoutx.EndIndent ();

        EditorGUILayoutx.BeginIndent ();
        graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation);
        EditorGUILayoutx.EndIndent ();

        EditorGUIUtility.LookLikeInspector ();

        graph.scale = EditorGUILayout.FloatField (new GUIContent ("Scale","Scale of the mesh"),graph.scale);
        graph.scale = (graph.scale < 0.01F && graph.scale > -0.01F) ? (graph.scale >= 0 ? 0.01F : -0.01F) : graph.scale;

        graph.accurateNearestNode = EditorGUILayout.Toggle (new GUIContent ("Accurate Nearest Node Queries","More accurate nearest node queries. See docs for more info"),graph.accurateNearestNode);
    }
コード例 #3
0
    public override void OnInspectorGUI(NavGraph target) {

        MyAStarPointGraph graph = target as MyAStarPointGraph;

        graph.maxDistance = EditorGUILayout.FloatField(new GUIContent("Max Distance", "The max distance in world space for a connection to be valid. A zero counts as infinity"), graph.maxDistance);

        EditorGUILayoutx.BeginIndent();
        graph.limits = EditorGUILayout.Vector3Field("Max Distance (axis aligned)", graph.limits);
        EditorGUILayoutx.EndIndent();

        graph.raycast = EditorGUILayout.Toggle(new GUIContent("Raycast", "Use raycasting to check if connections are valid between each pair of nodes"), graph.raycast);

        if (graph.raycast) {
            EditorGUI.indentLevel++;

            graph.thickRaycast = EditorGUILayout.Toggle(new GUIContent("Thick Raycast", "A thick raycast checks along a thick line with radius instead of just along a line"), graph.thickRaycast);

            if (graph.thickRaycast) {
                graph.thickRaycastRadius = EditorGUILayout.FloatField(new GUIContent("Raycast Radius", "The radius in world units for the thick raycast"), graph.thickRaycastRadius);
            }

            graph.mask = EditorGUILayoutx.LayerMaskField(/*new GUIContent (*/"Mask"/*,"Used to mask which layers should be checked")*/, graph.mask);
            EditorGUI.indentLevel--;
        }
    }
コード例 #4
0
ファイル: RecastGraphEditor.cs プロジェクト: Anaryu/aetherion
    /** Exports the INavmesh graph to a file */
    public void ExportToFile(NavGraph target)
    {
        INavmesh graph = (INavmesh)target;
        if (graph == null) return;

        Int3[] vertices = graph.vertices;

        if (vertices == null || target.nodes == null) {
            if (EditorUtility.DisplayDialog	 ("Scan graph before exporting?","The graph does not contain any mesh data. Do you want to scan it?","Ok","Cancel")) {
                AstarPath.MenuScan ();
            } else {
                return;
            }
        }

        vertices = graph.vertices;

        if (vertices == null || target.nodes == null) {
            Debug.LogError ("Graph still does not contain any nodes or vertices. Canceling");
            return;
        }

        string path = EditorUtility.SaveFilePanel ("Export .obj","","navmesh.obj","obj");

        if (path == "") return;

        //Generate .obj
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        string name = System.IO.Path.GetFileNameWithoutExtension (path);

        sb.Append ("g ").Append(name).AppendLine();

        //Write vertices
        for (int i=0;i<vertices.Length;i++) {
            Vector3 v = (Vector3)vertices[i];
            sb.Append(string.Format("v {0} {1} {2}\n",-v.x,v.y,v.z));
        }

        //Define single texture coordinate to zero
        sb.Append ("vt 0\n");

        //Write triangles
        for (int i=0;i<target.nodes.Length;i++) {
            MeshNode node = target.nodes[i] as MeshNode;
            if (node == null) {
                Debug.LogError ("Node could not be casted to MeshNode. Node was null or no MeshNode");
                return;
            }
            sb.Append(string.Format("f {0}/0 {1}/0 {2}/0\n", node.v1+1,node.v2+1,node.v3+1));
        }

        string obj = sb.ToString();

        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path))
        {
            sw.Write(obj);
        }
    }
コード例 #5
0
    //NavGraph imgNavGraph;
    //GridProperties gPropImgNav;
    //GridProperties gPropWorldNav;
    public ImgNavToWorldNavGraphBuilder(ref NavGraph para_imgNavGraph,
	                                    ref GridProperties para_gPropImgNavGraph,
	                                    ref GridProperties para_gPropWorldNavGraph)
    {
        //imgNavGraph = para_imgNavGraph;
        //gPropImgNav = para_gPropImgNavGraph;
        //gPropWorldNav = para_gPropWorldNavGraph;
    }
コード例 #6
0
    protected override float h_func(ref NavGraph para_graph, ref NavNode para_nodeID, ref NavNode para_goalNodeID)
    {
        WorldNode wN1 = (WorldNode) para_nodeID;
        WorldNode wN2 = (WorldNode) para_goalNodeID;

        float retHVal = UnityEngine.Vector3.Distance(wN1.getWorldPt(),wN2.getWorldPt());
        return retHVal;
    }
コード例 #7
0
    public override void OnInspectorGUI(NavGraph target)
    {
        PointGraph graph = target as PointGraph;

        /*
        #if UNITY_3_3
        graph.root = (Transform)EditorGUILayout.ObjectField (new GUIContent ("Root","All childs of this object will be used as nodes, if it is not set, a tag search will be used instead (see below)"),graph.root,typeof(Transform));
        #else
        graph.root = (Transform)EditorGUILayout.ObjectField (new GUIContent ("Root","All childs of this object will be used as nodes, if it is not set, a tag search will be used instead (see below)"),graph.root,typeof(Transform),true);
        #endif
        */
        //Debug.Log (EditorGUI.indentLevel);

        graph.root = ObjectField (new GUIContent ("Root","All childs of this object will be used as nodes, if it is not set, a tag search will be used instead (see below)"),graph.root,typeof(Transform),true) as Transform;

        graph.recursive = EditorGUILayout.Toggle (new GUIContent ("Recursive","Should childs of the childs in the root GameObject be searched"),graph.recursive);
        graph.searchTag = EditorGUILayout.TagField (new GUIContent ("Tag","If root is not set, all objects with this tag will be used as nodes"),graph.searchTag);

        if (graph.root != null) {
            GUILayout.Label ("All childs "+(graph.recursive ? "and sub-childs ":"") +"of 'root' will be used as nodes\nSet root to null to use a tag search instead",AstarPathEditor.helpBox);
        } else {
            GUILayout.Label ("All object with the tag '"+graph.searchTag+"' will be used as nodes"+(graph.searchTag == "Untagged" ? "\nNote: the tag 'Untagged' cannot be used" : ""),AstarPathEditor.helpBox);
        }

        graph.maxDistance = EditorGUILayout.FloatField (new GUIContent ("Max Distance","The max distance in world space for a connection to be valid. A zero counts as infinity"),graph.maxDistance);

        EditorGUIUtility.LookLikeControls ();
        #if UNITY_4_0
        graph.limits = EditorGUILayout.Vector3Field ("Max Distance (axis aligned)",graph.limits);
        #else
        EditorGUILayoutx.BeginIndent ();
        graph.limits = EditorGUILayout.Vector3Field ("Max Distance (axis aligned)",graph.limits);
        EditorGUILayoutx.EndIndent ();
        #endif
        EditorGUIUtility.LookLikeInspector ();

        graph.raycast = EditorGUILayout.Toggle (new GUIContent ("Raycast","Use raycasting to check if connections are valid between each pair of nodes"),graph.raycast);

        editor.GUILayoutx.BeginFadeArea (graph.raycast,"raycast");

            EditorGUI.indentLevel++;

         	graph.thickRaycast = EditorGUILayout.Toggle (new GUIContent ("Thick Raycast","A thick raycast checks along a thick line with radius instead of just along a line"),graph.thickRaycast);

         	editor.GUILayoutx.BeginFadeArea (graph.thickRaycast,"thickRaycast");

         		graph.thickRaycastRadius = EditorGUILayout.FloatField (new GUIContent ("Raycast Radius","The radius in world units for the thick raycast"),graph.thickRaycastRadius);

         	editor.GUILayoutx.EndFadeArea ();

            //graph.mask = 1 << EditorGUILayout.LayerField ("Mask",(int)Mathf.Log (graph.mask,2));
            graph.mask = EditorGUILayoutx.LayerMaskField (/*new GUIContent (*/"Mask"/*,"Used to mask which layers should be checked")*/,graph.mask);
            EditorGUI.indentLevel--;

        editor.GUILayoutx.EndFadeArea ();
    }
コード例 #8
0
    public override void OnInspectorGUI(NavGraph target)
    {
        base.OnInspectorGUI(target);
        Separator();

        MyGridGraph graph = target as MyGridGraph;

        GUILayout.BeginHorizontal();
        graph.levelLayerMask = EditorGUILayoutx.LayerMaskField("Level Layers", graph.levelLayerMask);
        GUILayout.EndHorizontal();
    }
コード例 #9
0
    public Graph_SearchDijkstra(NavGraph navGraph,
                       			int sourceNodeID,
                       			int targetNodeID = -1)
    {
        navGraph_ = navGraph;
        shortestPathTree_ = new NavGraphEdge[navGraph.NumNodes()];
        searchFrontier_ = new NavGraphEdge[navGraph.NumNodes()];
        costToThisNode_ = new float[navGraph.NumNodes()];
        sourceNodeID_ = sourceNodeID;
        targetNodeID_ = targetNodeID;

        Search();
    }
コード例 #10
0
	public void SerializeSettings (NavGraph target, AstarSerializer serializer) {
		//NavMeshGraph graph = target as NavMeshGraph;
		
		//string meshPath = AssetDatabase.GetAssetPath (graph.sourceMesh);
		//string meshGUID = AssetDatabase.AssetPathToGUID (meshPath);
		
		
		/*if (graph == null) {
			serializer.writerStream.Write (-1);
		} else {
			int instanceID = graph.sourceMesh != null ? graph.sourceMesh.GetInstanceID () : -1;
			serializer.writerStream.Write (instanceID);
		}*/
	}
コード例 #11
0
    protected override float g_func(ref NavGraph para_graph, ref NavNode para_node1, ref NavNode para_node2)
    {
        NavEdge reqEdge = para_graph.getEdge(para_node1.getNodeID(),para_node2.getNodeID());

        float retGVal = 0;
        if(reqEdge == null)
        {
            retGVal = float.PositiveInfinity;
        }
        else
        {
            retGVal = reqEdge.getCost();
        }
        return retGVal;
    }
コード例 #12
0
	//public GameObject meshRenderer;
	
	public override void OnInspectorGUI (NavGraph target) {
		NavMeshGraph graph = target as NavMeshGraph;
/*
#if UNITY_3_3
		graph.sourceMesh = EditorGUILayout.ObjectField ("Source Mesh",graph.sourceMesh,typeof(Mesh)) as Mesh;
#else
		graph.sourceMesh = EditorGUILayout.ObjectField ("Source Mesh",graph.sourceMesh,typeof(Mesh), true) as Mesh;
#endif
*/
		graph.sourceMesh = ObjectField ("Source Mesh", graph.sourceMesh, typeof(Mesh), false) as Mesh;
		
		graph.offset = EditorGUILayout.Vector3Field ("Offset",graph.offset);
		graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation);
		graph.scale = EditorGUILayout.FloatField (new GUIContent ("Scale","Scale of the mesh"),graph.scale);
		graph.scale = (graph.scale < 0.01F && graph.scale > -0.01F) ? (graph.scale >= 0 ? 0.01F : -0.01F) : graph.scale;
	}
コード例 #13
0
    public Graph_SearchAStar_TS(NavGraph graph, int source, int target)
        : base(SearchType.AStar)
    {
        graph_ = graph;
        shortestPathTree_ = new NavGraphEdge[graph.NumNodes()];
        searchFrontier_ = new NavGraphEdge[graph.NumNodes()];
        gCosts_ = new float[graph.NumNodes()];
        fCosts_ = new float[graph.NumNodes()];
        sourceIdx_ = source;
        targetIdx_ = target;

         	//create the PQ
         	pq_ = new IndexedPriorityQLow(fCosts_, graph_.NumNodes());

        //put the source node on the queue
        pq_.Insert(sourceIdx_);
    }
コード例 #14
0
	public void DeSerializeSettings (NavGraph target, AstarSerializer serializer) {
		//NavMeshGraph graph = target as NavMeshGraph;
		
		//string meshGUID = serializer.readerStream.ReadString ();
		//int instanceID = serializer.readerStream.ReadInt32 ();
		
		//Mesh ob = EditorUtility.InstanceIDToObject (instanceID) as Mesh;
		
		//if (!Application.isPlaying) {
			//graph.sourceMesh = ob;
			/*string meshPath = AssetDatabase.GUIDToAssetPath (meshGUID);
			Debug.Log (meshGUID +" "+ meshPath);
			graph.sourceMesh = AssetDatabase.LoadAssetAtPath (meshPath,typeof(Mesh)) as Mesh;*/
		//}
		
		//Debug.Log ("Did succeed? "+(graph.sourceMesh != null));
	}
コード例 #15
0
    public Graph_SearchDijkstras_TS(	NavGraph navGraph,
                          				int sourceNodeIndex,
                          				int targetNodeIndex)
        : base(Graph_SearchTimeSliced.SearchType.Dijkstra)
    {
        navGraph_ = navGraph;
        shortestPathTree_ = new NavGraphEdge[navGraph_.NumNodes()];
        searchFrontier_ = new NavGraphEdge[navGraph_.NumNodes()];
        costToThisNode_ = new float[navGraph_.NumNodes()];
        sourceNodeIndex_ = sourceNodeIndex;
        targetNodeIndex_ = targetNodeIndex;

         	//create the PQ         ,
         	pq_ = new IndexedPriorityQLow( costToThisNode_, navGraph_.NumNodes() );

        //put the source node on the queue
        pq_.Insert( sourceNodeIndex_ );
    }
コード例 #16
0
ファイル: LayerGridGraphEditor.cs プロジェクト: klobodnf/st1
    public override void OnInspectorGUI(NavGraph target)
    {
        LayerGridGraph graph = target as LayerGridGraph;

        graph.mergeSpanRange = EditorGUILayout.FloatField ("Merge Span Range",graph.mergeSpanRange);
        graph.characterHeight = EditorGUILayout.FloatField ("Character Height",graph.characterHeight);
        graph.maxClimb = Mathf.Clamp (EditorGUILayout.FloatField ("Max climb",graph.maxClimb),0,graph.characterHeight);

        graph.neighbours = NumNeighbours.Four;
        textureVisible = false;
        base.OnInspectorGUI (target);

        if (graph.neighbours != NumNeighbours.Four) {
            Debug.Log ("Note: Only 4 neighbours per grid node is allowed in this graph type");
        }

        if (graph.collision.thickRaycast)
            HelpBox ("Note: Thick raycast cannot be used with this graph type");
    }
コード例 #17
0
        static AutoWalker()
        {
            GameID   = DateTime.Now.Ticks + "" + RandomString(10);
            newPF    = MainMenu.GetMenu("AB").Get <CheckBox>("newPF").CurrentValue;
            NavGraph = new NavGraph(Path.Combine(Environment.GetFolderPath(
                                                     Environment.SpecialFolder.ApplicationData), "AutoBuddy"));
            PfNodes    = new List <Vector3>();
            color      = new ColorBGRA(79, 219, 50, 255);
            MyNexus    = ObjectManager.Get <Obj_HQ>().First(n => n.IsAlly);
            EneMyNexus = ObjectManager.Get <Obj_HQ>().First(n => n.IsEnemy);
            EnemyLazer =
                ObjectManager.Get <Obj_AI_Turret>().FirstOrDefault(tur => !tur.IsAlly && tur.GetLane() == Lane.Spawn);
            p = ObjectManager.Player;
            initSummonerSpells();

            Target = ObjectManager.Player.Position;
            Orbwalker.DisableMovement = false;

            Orbwalker.DisableAttacking = false;
            Game.OnUpdate += Game_OnUpdate;
            Orbwalker.OverrideOrbwalkPosition = () => Target;
            if (Orbwalker.HoldRadius > 130 || Orbwalker.HoldRadius < 80)
            {
                Chat.Print("=================WARNING=================", Color.Red);
                Chat.Print("Your hold radius value in orbwalker isn't optimal for AutoBuddy", Color.Aqua);
                Chat.Print("Please set hold radius through menu=>Orbwalker");
                Chat.Print("Recommended values: Hold radius: 80-130, Delay between movements: 100-250");
            }
            if (MainMenu.GetMenu("AB").Get <CheckBox>("debuginfo").CurrentValue)
            {
                Drawing.OnDraw += Drawing_OnDraw;
            }

            Core.DelayAction(OnEndGame, 20000);
            updateItems();
            oldOrbwalk();
            EloBuddy.SDK.Events.Teleport.OnTeleport += Teleport_OnTeleport;
            Game.OnTick += OnTick;
        }
コード例 #18
0
    public Vector3 GetClampedPoint(Vector3 from, Vector3 to, Node hint)
    {
        //float minDistance = Mathf.Infinity;
        Vector3 minPoint = to;

        if (useRaycasting)
        {
            RaycastHit hit;
            if (Physics.Linecast(from, to, out hit, mask))
            {
                minPoint = hit.point;
                //minDistance = hit.distance;
            }
        }

        if (useGraphRaycasting && hint != null)
        {
            NavGraph graph = AstarData.GetGraph(hint);

            if (graph != null)
            {
                IRaycastableGraph rayGraph = graph as IRaycastableGraph;

                if (rayGraph != null)
                {
                    GraphHitInfo hit;

                    if (rayGraph.Linecast(from, minPoint, hint, out hit))
                    {
                        //if ((hit.point-from).magnitude < minDistance) {
                        minPoint = hit.point;
                        //}
                    }
                }
            }
        }

        return(minPoint);
    }
コード例 #19
0
    public override void OnInspectorGUI(NavGraph target)
    {
        LayerGridGraph graph = target as LayerGridGraph;

        graph.mergeSpanRange  = EditorGUILayout.FloatField("Merge Span Range", graph.mergeSpanRange);
        graph.characterHeight = EditorGUILayout.FloatField("Character Height", graph.characterHeight);
        graph.maxClimb        = Mathf.Clamp(EditorGUILayout.FloatField("Max climb", graph.maxClimb), 0, graph.characterHeight);

        graph.neighbours = NumNeighbours.Four;
        textureVisible   = false;
        base.OnInspectorGUI(target);

        if (graph.neighbours != NumNeighbours.Four)
        {
            Debug.Log("Note: Only 4 neighbours per grid node is allowed in this graph type");
        }

        if (graph.collision.thickRaycast)
        {
            HelpBox("Note: Thick raycast cannot be used with this graph type");
        }
    }
コード例 #20
0
        /** Serialize node connections for given graph index.
         * Connections structure is as follows. Bracket structure has nothing to do with data, just how it is structured:\n
         * \code
         * for every node {
         * Int32 NodeIndex
         * Int16 ConnectionCount
         * for every connection of the node {
         * Int32 OtherNodeIndex
         * Int32 ConnectionCost
         * }
         * }
         * \endcode
         */
        private byte[] SerializeNodeConnections(int index)
        {
            NavGraph     graph  = graphs[index];
            MemoryStream str    = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(str);

            if (graph.nodes == null)
            {
                return(new byte[0]);
            }

            Node[] nodes = graph.nodes;

            for (int i = 0; i < nodes.Length; i++)
            {
                Node node = nodes[i];
                if (node.connections == null)
                {
                    writer.Write((ushort)0); continue;
                }

                if (node.connections.Length != node.connectionCosts.Length)
                {
                    throw new IndexOutOfRangeException("Node.connections.Length != Node.connectionCosts.Length. In node " + i + " in graph " + index);
                }

                //writer.Write(node.GetNodeIndex());
                writer.Write((ushort)node.connections.Length);

                for (int j = 0; j < node.connections.Length; j++)
                {
                    writer.Write(node.connections[j].GetNodeIndex());
                    writer.Write(node.connectionCosts[j]);
                }
            }

            writer.Close();
            return(str.ToArray());
        }
コード例 #21
0
ファイル: HexGraphEditor.cs プロジェクト: GroDany/EIP
    public override void OnInspectorGUI(NavGraph target)
    {
        PointGraph graph = target as PointGraph;

        graph.root = ObjectField(new GUIContent("Root", "All children of this object will be used as nodes, if it is not set, a tag search will be used instead (see below)"), graph.root, typeof(Transform), true) as Transform;

        graph.recursive = EditorGUILayout.Toggle(new GUIContent("Recursive", "Should children of the children in the root GameObject be searched"), graph.recursive);
        graph.searchTag = EditorGUILayout.TagField(new GUIContent("Tag", "If root is not set, all objects with this tag will be used as nodes"), graph.searchTag);

        if (graph.root != null)
        {
            EditorGUILayout.HelpBox("All children " + (graph.recursive ? "and sub-children " : "") + "of 'root' will be used as nodes\nSet root to null to use a tag search instead", MessageType.None);
        }
        else
        {
            EditorGUILayout.HelpBox("All object with the tag '" + graph.searchTag + "' will be used as nodes" + (graph.searchTag == "Untagged" ? "\nNote: the tag 'Untagged' cannot be used" : ""), MessageType.None);
        }

        graph.maxDistance = EditorGUILayout.FloatField(new GUIContent("Max Distance", "The max distance in world space for a connection to be valid. A zero counts as infinity"), graph.maxDistance);

        graph.limits  = EditorGUILayout.Vector3Field("Max Distance (axis aligned)", graph.limits);
        graph.raycast = EditorGUILayout.Toggle(new GUIContent("Raycast", "Use raycasting to check if connections are valid between each pair of nodes"), graph.raycast);

        if (graph.raycast)
        {
            EditorGUI.indentLevel++;

            graph.thickRaycast = EditorGUILayout.Toggle(new GUIContent("Thick Raycast", "A thick raycast checks along a thick line with radius instead of just along a line"), graph.thickRaycast);

            if (graph.thickRaycast)
            {
                graph.thickRaycastRadius = EditorGUILayout.FloatField(new GUIContent("Raycast Radius", "The radius in world units for the thick raycast"), graph.thickRaycastRadius);
            }

            graph.mask = EditorGUILayoutx.LayerMaskField(/*new GUIContent (*/ "Mask" /*,"Used to mask which layers should be checked")*/, graph.mask);
            EditorGUI.indentLevel--;
        }
    }
コード例 #22
0
        public void InitPhysicsManager()
        {
            //find all colliders in the scene A$AP
            boxList = GameObject.FindGameObjectsWithTag("Ground");
            for (int i = 0; i < boxList.Length; i++)
            {
                floorBoundingBoxes.Add(boxList[i].GetComponent <AABB>());
            }
            boxList = null;
            boxList = GameObject.FindGameObjectsWithTag("Entity");
            for (int i = 0; i < boxList.Length; i++)
            {
                entityBoundingBoxes.Add(boxList[i].GetComponent <AABB>());
            }
            // add player collider
            entityBoundingBoxes.Add(GameObject.FindGameObjectWithTag("Player").GetComponent <AABB>());

            boxList = null;
            boxList = GameObject.FindGameObjectsWithTag("Boundary");
            for (int i = 0; i < boxList.Length; i++)
            {
                boundaryBoundingBoxes.Add(boxList[i].GetComponent <AABB>());
            }
            // initialise collision data
            colPair = new CollisionPair();

            // initialise all rigidbodies in scene
            InitRigidbodiesInScene();

            // initialise nav graph
            grid = GetComponent <NavGraph>();
            grid.InitGraph();

            chargeRate = 0;
            chargeDmg  = 0;

            dPath = new List <Vector2>();
        }
コード例 #23
0
        static AutoWalker()
        {
            Chat.Print("Game Mode: " + BrutalExtensions.GetGameMode());
            newPF      = MainMenu.GetMenu("AB").Get <CheckBox>("newPF").CurrentValue;
            NavGraph   = new NavGraph(Path.Combine(SandboxConfig.DataDirectory, "AutoBuddy"));
            PfNodes    = new List <Vector3>();
            color      = new ColorBGRA(79, 219, 50, 255);
            MyNexus    = ObjectManager.Get <Obj_HQ>().First(n => n.IsAlly);
            EneMyNexus = ObjectManager.Get <Obj_HQ>().First(n => n.IsEnemy);
            EnemyLazer = ObjectManager.Get <Obj_AI_Turret>().FirstOrDefault(tur => !tur.IsAlly && tur.GetLane() == Lane.Spawn);
            p          = ObjectManager.Player;
            initSummonerSpells();

            Target = ObjectManager.Player.Position;
            Orbwalker.DisableMovement = false;
            Game.OnUpdate            += Game_OnUpdate;

            if (!MainMenu.GetMenu("AB").Get <CheckBox>("disableAutoBuddy").CurrentValue)
            {
                Orbwalker.OverrideOrbwalkPosition = () => Target;
            }
            if (Orbwalker.HoldRadius > 130 || Orbwalker.HoldRadius < 80)
            {
                Chat.Print("=================WARNING=================", Color.Red);
                Chat.Print("Your hold radius value in orbwalker isn't optimal for AutoBuddy", Color.Aqua);
                Chat.Print("Please set hold radius through menu=>Orbwalker");
                Chat.Print("Recommended values: Hold radius: 80-130, Delay between movements: 100-250");
            }
            if (MainMenu.GetMenu("AB").Get <CheckBox>("debuginfo").CurrentValue)
            {
                Drawing.OnDraw += Drawing_OnDraw;
            }

            updateItems();
            oldOrbwalk();
            Game.OnTick += OnTick;
            Game.OnTick += GameEndHandler;
        }
コード例 #24
0
        private bool AnyDestroyedNodesInGraphs()
        {
            bool result = false;

            Action <GraphNode> < > 9__0;
            for (int i = 0; i < this.graphs.Length; i++)
            {
                NavGraph           navGraph = this.graphs[i];
                Action <GraphNode> action;
                if ((action = < > 9__0) == null)
                {
                    action = (< > 9__0 = delegate(GraphNode node)
                    {
                        if (node.Destroyed)
                        {
                            result = true;
                        }
                    });
                }
                navGraph.GetNodes(action);
            }
            return(result);
        }
コード例 #25
0
    // will return false if any part of the line is off the nav mesh
    // if 'clampFromInNavMesh' is true, we make sure the from position is on the nav mesh before doing checks
    // (done in 2d, does not currently support nav meshes on top of one and other)
    public static bool IsVisibleOnRecastGraph(Vector3 from, Vector3 to, bool clampFromInNavMesh = false, NNInfo?nearestInfo = null)
    {
        if (null == AstarPath.active)
        {
            return(false);
        }

        NNInfo fromInfo = nearestInfo ?? AstarPath.active.GetNearest(from);

        if (null == fromInfo.node)
        {
            return(false);
        }

        if (clampFromInNavMesh)
        {
            from = CalculatePointOnRecastGraph(from, 0.1f, fromInfo);
        }

        NavGraph graph = AstarData.GetGraph(fromInfo.node);

        if (graph != null)
        {
            IRaycastableGraph rayGraph = graph as IRaycastableGraph;
            if (rayGraph != null)
            {
                GraphHitInfo hit;
                if (rayGraph.Linecast(from, to, fromInfo.node, out hit))
                {
                    return(false); // hit an obstacle
                }
                return(true);      // no nav mesh exit
            }
            return(false);         // no recast graph
        }
        return(false);             // no nav mesh
    }
コード例 #26
0
ファイル: PathFinder.cs プロジェクト: YiuWingTan/Raven
        public void Search(int source, int target, NavGraph graph)
        {
            this.source = source;

            this.Target = target;

            this.graph = graph;

            path = new List <int>();

            pathIndex = new int[graph.ActiveV];

            hasVisited = new bool[graph.ActiveV];

            isHavePath = search(source, target);

            if (isHavePath)
            {
                Stack <int> p = new Stack <int>();

                p.Push(target);

                int n = target;
                while (pathIndex[n] != source)
                {
                    p.Push(pathIndex[n]);
                    n = pathIndex[n];
                }

                p.Push(source);

                while (p.Count != 0)
                {
                    path.Add(p.Pop());
                }
            }
        }
コード例 #27
0
        public static void ScanGraph(NavGraph graph)
        {
            if (AstarPath.OnGraphPreScan != null)
            {
                AstarPath.OnGraphPreScan(graph);
            }

            graph.Scan();

            int index = AstarPath.active.astarData.GetGraphIndex(graph);

            if (index < 0)
            {
                throw new System.ArgumentException("Graph is not added to AstarData");
            }

            if (graph.nodes != null)
            {
                for (int j = 0; j < graph.nodes.Length; j++)
                {
                    if (graph.nodes[j] != null)
                    {
                        graph.nodes[j].graphIndex = index;
                    }
                }
            }

            if (AstarPath.OnGraphPostScan != null)
            {
                AstarPath.OnGraphPostScan(graph);
            }

            AstarPath.active.FloodFill();

            AstarPath.active.DataUpdate();
        }
コード例 #28
0
    public override void OnInspectorGUI(NavGraph target)
    {
        GridGraph graph = target as GridGraph;

        //GUILayout.BeginHorizontal ();
        //GUILayout.BeginVertical ();
        Rect lockRect;
        Rect tmpLockRect;

        GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle("GridSizeLock");

        if (lockStyle == null)
        {
            lockStyle = new GUIStyle();
        }

        bool sizeSelected1 = false;
        bool sizeSelected2 = false;
        int  newWidth      = IntField("Width (nodes)", graph.width, 50, 0, out lockRect, out sizeSelected1);
        int  newDepth      = IntField("Depth (nodes)", graph.depth, 50, 0, out tmpLockRect, out sizeSelected2);

        //Rect r = GUILayoutUtility.GetRect (0,0,lockStyle);

        lockRect.width  = lockStyle.fixedWidth;
        lockRect.height = lockStyle.fixedHeight;
        lockRect.x     += lockStyle.margin.left;
        lockRect.y     += lockStyle.margin.top;

        locked = GUI.Toggle(lockRect, locked, new GUIContent("", "If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"), lockStyle);

        //GUILayout.EndHorizontal ();



        if (newWidth != graph.width || newDepth != graph.depth)
        {
            SnapSizeToNodes(newWidth, newDepth, graph);
        }

        GUI.SetNextControlName("NodeSize");
        newNodeSize = EditorGUILayout.FloatField("Node size", graph.nodeSize);

        newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize;

        //if ((GUI.GetNameOfFocusedControl () != "NodeSize" && Event.current.type == EventType.Repaint) || Event.current.keyCode == KeyCode.Return) {

        //Debug.Log ("Node Size Not Selected " + Event.current.type);

        if (graph.nodeSize != newNodeSize)
        {
            if (!locked)
            {
                graph.nodeSize = newNodeSize;
                Matrix4x4 oldMatrix = graph.matrix;
                graph.GenerateMatrix();
                if (graph.matrix != oldMatrix)
                {
                    //Rescann the graphs
                    //AstarPath.active.AutoScan ();
                    GUI.changed = true;
                }
            }
            else
            {
                float delta = newNodeSize / graph.nodeSize;
                graph.nodeSize      = newNodeSize;
                graph.unclampedSize = new Vector2(newWidth * graph.nodeSize, newDepth * graph.nodeSize);
                Vector3 newCenter = graph.matrix.MultiplyPoint3x4(new Vector3((newWidth / 2F) * delta, 0, (newDepth / 2F) * delta));
                graph.center = newCenter;
                graph.GenerateMatrix();

                //Make sure the width & depths stay the same
                graph.width = newWidth;
                graph.depth = newDepth;
                AstarPath.active.AutoScan();
            }
        }
        //}

        Vector3 pivotPoint;
        Vector3 diff;

        GUILayout.BeginHorizontal();

        switch (pivot)
        {
        case GridPivot.Center:
            graph.center = EditorGUILayout.Vector3Field("Center", graph.center);
            break;

        case GridPivot.TopLeft:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(0, 0, graph.depth));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Top-Left", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.TopRight:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(graph.width, 0, graph.depth));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Top-Right", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.BottomLeft:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(0, 0, 0));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Bottom-Left", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.BottomRight:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(graph.width, 0, 0));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Bottom-Right", pivotPoint);
            graph.center = pivotPoint - diff;
            break;
        }

        graph.GenerateMatrix();

        pivot = PivotPointSelector(pivot);

        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        graph.rotation = EditorGUILayout.Vector3Field("Rotation", graph.rotation);
        //Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector)
        GUILayout.Space(19 + 4 + 7);
        GUILayout.EndHorizontal();

        if (GUILayout.Button(new GUIContent("Snap Size", "Snap the size to exactly fit nodes"), GUILayout.MaxWidth(100), GUILayout.MaxHeight(16)))
        {
            SnapSizeToNodes(newWidth, newDepth, graph);
        }

        Separator();

        graph.cutCorners = EditorGUILayout.Toggle("Cut Corners", graph.cutCorners);
        graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup("Connections", graph.neighbours);

        //GUILayout.BeginHorizontal ();
        //EditorGUILayout.PrefixLabel ("Max Climb");
        graph.maxClimb = EditorGUILayout.FloatField("Max Climb", graph.maxClimb);
        EditorGUI.indentLevel++;
        graph.maxClimbAxis = EditorGUILayout.IntPopup("Climb Axis", graph.maxClimbAxis, new string[3] {
            "X", "Y", "Z"
        }, new int[3] {
            0, 1, 2
        });

        EditorGUI.indentLevel--;
        //GUILayout.EndHorizontal ();

        GUILayout.BeginHorizontal();
        bool preEnabled = GUI.enabled;

        GUI.enabled            = graph.useRaycastNormal;
        graph.maxSlope         = EditorGUILayout.Slider("Max Slope", graph.maxSlope, 0, 90F);
        GUI.enabled            = preEnabled;
        graph.useRaycastNormal = GUILayout.Toggle(graph.useRaycastNormal, new GUIContent("", "Use the heigh raycast's normal to figure out the slope of the ground and check if it flat enough to stand on"), GUILayout.Width(10));
        GUILayout.EndHorizontal();

        graph.erodeIterations = EditorGUILayout.IntField("Erode iterations", graph.erodeIterations);
        graph.erodeIterations = graph.erodeIterations > 16 ? 16 : graph.erodeIterations;         //Clamp iterations to 16

        DrawCollisionEditor(graph.collision);

        Separator();

        showExtra = EditorGUILayout.Foldout(showExtra, "Extra");

        if (showExtra)
        {
            EditorGUI.indentLevel += 2;

            graph.penaltyAngle = ToggleGroup("Angle Penalty", graph.penaltyAngle);
            //bool preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyAngle && GUI.enabled;
            if (graph.penaltyAngle)
            {
                EditorGUI.indentLevel++;
                graph.penaltyAngleFactor = EditorGUILayout.FloatField("Factor", graph.penaltyAngleFactor);
                //GUI.enabled = preGUI;
                HelpBox("Applies penalty to nodes based on the angle of the hit surface during the Height Testing");

                EditorGUI.indentLevel--;
            }

            graph.penaltyPosition = ToggleGroup("Position Penalty", graph.penaltyPosition);
            //EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition);
            //preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyPosition && GUI.enabled;
            if (graph.penaltyPosition)
            {
                EditorGUI.indentLevel++;
                graph.penaltyPositionOffset = EditorGUILayout.FloatField("Offset", graph.penaltyPositionOffset);
                graph.penaltyPositionFactor = EditorGUILayout.FloatField("Factor", graph.penaltyPositionFactor);
                HelpBox("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first (usually 100)");
                //GUI.enabled = preGUI;
                EditorGUI.indentLevel--;
            }

            GUI.enabled = false;
            ToggleGroup(new GUIContent("Use Texture", AstarPathEditor.AstarProTooltip), false);
            GUI.enabled            = true;
            EditorGUI.indentLevel -= 2;
        }
    }
コード例 #29
0
    public override void OnInspectorGUI(NavGraph target)
    {
        GridGraph graph = target as GridGraph;

        //GUILayout.BeginHorizontal ();
        //GUILayout.BeginVertical ();
        Rect lockRect;
        Rect tmpLockRect;

        GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle ("GridSizeLock");
        if (lockStyle == null) {
            lockStyle = new GUIStyle ();
        }

        bool sizeSelected1 = false;
        bool sizeSelected2 = false;
        int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,50,0, out lockRect, out sizeSelected1);
        int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,50,0, out tmpLockRect, out sizeSelected2);

        //Rect r = GUILayoutUtility.GetRect (0,0,lockStyle);

        lockRect.width = lockStyle.fixedWidth;
        lockRect.height = lockStyle.fixedHeight;
        lockRect.x += lockStyle.margin.left;
        lockRect.y += lockStyle.margin.top;

        locked = GUI.Toggle (lockRect,locked,new GUIContent ("","If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"),lockStyle);

        //GUILayout.EndHorizontal ();

        if (newWidth != graph.width || newDepth != graph.depth) {
            SnapSizeToNodes (newWidth,newDepth,graph);
        }

        GUI.SetNextControlName ("NodeSize");
        newNodeSize = EditorGUILayout.FloatField (new GUIContent ("Node size","The size of a single node. The size is the side of the node square in world units"),graph.nodeSize);

        newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize;

        float prevRatio = graph.aspectRatio;
        graph.aspectRatio = EditorGUILayout.FloatField (new GUIContent ("Aspect Ratio","Scaling of the nodes width/depth ratio. Good for isometric games"),graph.aspectRatio);

        //if ((GUI.GetNameOfFocusedControl () != "NodeSize" && Event.current.type == EventType.Repaint) || Event.current.keyCode == KeyCode.Return) {

            //Debug.Log ("Node Size Not Selected " + Event.current.type);

            if (graph.nodeSize != newNodeSize || prevRatio != graph.aspectRatio) {
                if (!locked) {
                    graph.nodeSize = newNodeSize;
                    Matrix4x4 oldMatrix = graph.matrix;
                    graph.GenerateMatrix ();
                    if (graph.matrix != oldMatrix) {
                        //Rescann the graphs
                        //AstarPath.active.AutoScan ();
                        GUI.changed = true;
                    }
                } else {
                    float delta = newNodeSize / graph.nodeSize;
                    graph.nodeSize = newNodeSize;
                    graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize);
                    Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 ((newWidth/2F)*delta,0,(newDepth/2F)*delta));
                    graph.center = newCenter;
                    graph.GenerateMatrix ();

                    //Make sure the width & depths stay the same
                    graph.width = newWidth;
                    graph.depth = newDepth;
                    AstarPath.active.AutoScan ();
                }
            }
        //}

        Vector3 pivotPoint;
        Vector3 diff;

        EditorGUIUtility.LookLikeControls ();
        EditorGUILayoutx.BeginIndent ();

        switch (pivot) {
            case GridPivot.Center:
                graph.center = EditorGUILayout.Vector3Field ("Center",graph.center);
                break;
            case GridPivot.TopLeft:
                pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,graph.depth));
                diff = pivotPoint-graph.center;
                pivotPoint = EditorGUILayout.Vector3Field ("Top-Left",pivotPoint);
                graph.center = pivotPoint-diff;
                break;
            case GridPivot.TopRight:
                pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,graph.depth));
                diff = pivotPoint-graph.center;
                pivotPoint = EditorGUILayout.Vector3Field ("Top-Right",pivotPoint);
                graph.center = pivotPoint-diff;
                break;
            case GridPivot.BottomLeft:
                pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,0));
                diff = pivotPoint-graph.center;
                pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Left",pivotPoint);
                graph.center = pivotPoint-diff;
                break;
            case GridPivot.BottomRight:
                pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,0));
                diff = pivotPoint-graph.center;
                pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Right",pivotPoint);
                graph.center = pivotPoint-diff;
                break;
        }

        graph.GenerateMatrix ();

        pivot = PivotPointSelector (pivot);

        EditorGUILayoutx.EndIndent ();

        EditorGUILayoutx.BeginIndent ();

        graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation);
        //Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector)
        GUILayout.Space (19+7);
        //GUILayout.EndHorizontal ();

        EditorGUILayoutx.EndIndent ();
        EditorGUIUtility.LookLikeInspector ();

        if (GUILayout.Button (new GUIContent ("Snap Size","Snap the size to exactly fit nodes"),GUILayout.MaxWidth (100),GUILayout.MaxHeight (16))) {
            SnapSizeToNodes (newWidth,newDepth,graph);
        }

        Separator ();

        graph.cutCorners = EditorGUILayout.Toggle (new GUIContent ("Cut Corners","Enables or disables cutting corners. See docs for image example"),graph.cutCorners);
        graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup (new GUIContent ("Connections","Sets how many connections a node should have to it's neighbour nodes."),graph.neighbours);

        //GUILayout.BeginHorizontal ();
        //EditorGUILayout.PrefixLabel ("Max Climb");
        graph.maxClimb = EditorGUILayout.FloatField (new GUIContent ("Max Climb","How high, relative to the graph, should a climbable level be. A zero (0) indicates infinity"),graph.maxClimb);
        EditorGUI.indentLevel++;
        graph.maxClimbAxis = EditorGUILayout.IntPopup (new GUIContent ("Climb Axis","Determines which axis the above setting should test on"),graph.maxClimbAxis,new GUIContent[3] {new GUIContent ("X"),new GUIContent ("Y"),new GUIContent ("Z")},new int[3] {0,1,2});

        EditorGUI.indentLevel--;
        //GUILayout.EndHorizontal ();

        GUILayout.BeginHorizontal ();
        //bool preEnabled = GUI.enabled;
        //GUI.enabled = graph.useRaycastNormal;
        graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Sets the max slope in degrees for a point to be walkable"),graph.maxSlope,0,90F);
        //GUI.enabled = preEnabled;
        //graph.useRaycastNormal = Mathf.Abs (90-graph.maxSlope) > float.Epsilon;
        //GUILayout.Toggle (graph.useRaycastNormal,new GUIContent ("","Use the heigh raycast's normal to figure out the slope of the ground and check if it flat enough to stand on"),GUILayout.Width (10));
        GUILayout.EndHorizontal ();

        graph.erodeIterations = EditorGUILayout.IntField (new GUIContent ("Erode iterations","Sets how many times the graph should be eroded. This adds extra margin to objects. This will not work when using Graph Updates, so if you can, use the Diameter setting in collision settings instead"),graph.erodeIterations);
        graph.erodeIterations = graph.erodeIterations > 16 ? 16 : graph.erodeIterations; //Clamp iterations to 16

        graph.erosionUseTags = EditorGUILayout.Toggle (new GUIContent ("Erosion Uses Tags","Instead of making nodes unwalkable, " +
            "nodes will have their tag set to a value corresponding to their erosion level, " +
            "which is a quite good measurement of their distance to the closest wall."),
                                                       graph.erosionUseTags);
        if (graph.erosionUseTags) {
            EditorGUI.indentLevel++;
            graph.erosionFirstTag = EditorGUILayoutx.SingleTagField ("First Tag",graph.erosionFirstTag);
            EditorGUI.indentLevel--;
        }

        DrawCollisionEditor (graph.collision);

        Separator ();

        showExtra = EditorGUILayout.Foldout (showExtra, "Extra");

        if (showExtra) {
            EditorGUI.indentLevel+=2;

            graph.penaltyAngle = ToggleGroup (new GUIContent ("Angle Penalty","Adds a penalty based on the slope of the node"),graph.penaltyAngle);
            //bool preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyAngle && GUI.enabled;
            if (graph.penaltyAngle) {
                EditorGUI.indentLevel++;
                graph.penaltyAngleFactor = EditorGUILayout.FloatField (new GUIContent ("Factor","Scale of the penalty. A negative value should not be used"),graph.penaltyAngleFactor);
                //GUI.enabled = preGUI;
                HelpBox ("Applies penalty to nodes based on the angle of the hit surface during the Height Testing");

                EditorGUI.indentLevel--;
            }

            graph.penaltyPosition = ToggleGroup ("Position Penalty",graph.penaltyPosition);
                //EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition);
            //preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyPosition && GUI.enabled;
            if (graph.penaltyPosition) {
                EditorGUI.indentLevel++;
                graph.penaltyPositionOffset = EditorGUILayout.FloatField ("Offset",graph.penaltyPositionOffset);
                graph.penaltyPositionFactor = EditorGUILayout.FloatField ("Factor",graph.penaltyPositionFactor);
                HelpBox ("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first ("+Int3.Precision+")\n" +
                    "Be very careful when using negative values since a negative penalty will underflow and instead get really high");
                //GUI.enabled = preGUI;
                EditorGUI.indentLevel--;
            }

            GUI.enabled = false;
            ToggleGroup (new GUIContent ("Use Texture",AstarPathEditor.AstarProTooltip),false);
            GUI.enabled = true;
            EditorGUI.indentLevel-=2;
        }
    }
コード例 #30
0
ファイル: GraphEditor.cs プロジェクト: jlonardi/igp-DnM
 /** Override to implement graph inspectors */
 public virtual void OnInspectorGUI(NavGraph target)
 {
 }
コード例 #31
0
ファイル: GraphEditor.cs プロジェクト: jlonardi/igp-DnM
    /*public void OnDisableUndo () {
        return;
        if (!editor.enableUndo) {
            return;
        }

        if (undoState != null) {
            ScriptableObject.DestroyImmediate (undoState);
            undoState = null;
        }
    }

    private void ApplyUndo () {
        return;
        if (!editor.enableUndo) {
            return;
        }

        undoState.hasBeenReverted = false;

        if (AstarPath.active == null) {
            return;
        }

        byte[] bytes = GetSerializedBytes (target);

        bool isDifferent = false;

        //Check if the data is any different from the last saved data, if it isn't, don't load it
        if (undoState.data == null || bytes.Length != undoState.data.Length) {
            isDifferent = true;
        } else {
            for (int i=0;i<bytes.Length;i++) {
                if (bytes[i] != undoState.data[i]) {
                    isDifferent = true;
                    break;
                }
            }
        }

        if (isDifferent) {

            Debug.Log ("The undo is different "+ Event.current.type +" "+Event.current.commandName);
            //Event.current.Use ();
            AstarSerializer sz = new AstarSerializer (editor.script);
            sz.OpenDeserialize (undoState.data);
            sz.DeSerializeSettings (target,AstarPath.active);
            sz.Close ();
        }
    }

    public void ModifierKeysChanged () {
        return;
        if (!editor.enableUndo) {
            return;
        }

        if (undoState == null) {
            return;
        }
        //The user has tried to undo something, apply that
        if (undoState.hasBeenReverted) {
            ApplyUndo ();
            GUI.changed = true;
            editor.Repaint ();
        }

    }

    /** Handles undo operations for the graph *
    public void HandleUndo (NavGraph target) {
        return;
        if (!editor.enableUndo) {
            return;
        }

        if (undoState == null) {
            undoState = ScriptableObject.CreateInstance<GraphUndo>();
        }

        Event e = Event.current;

        //ModifierKeysChanged ();

        //To serialize settings for a grid graph takes from 0.00 ms to 7.8 ms (usually 0.0, but sometimes jumps up to 7.8 (no values in between)
        if ((e.button == 0 && (e.type == EventType.MouseDown || e.type == EventType.MouseUp)) || (e.isKey && (e.keyCode == KeyCode.Tab || e.keyCode == KeyCode.Return))) {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            //Serialize the settings of the graph
            byte[] bytes = GetSerializedBytes (target);

            bool isDifferent = false;

            if (undoState.data == null) {
                Debug.LogError ("UndoState.data == null - This should not happen");
                return;
            }

            //Check if the data is any different from the last saved data, if it isn't, don't save it
            if (bytes.Length != undoState.data.Length) {
                isDifferent = true;
            } else {
                for (int i=0;i<bytes.Length;i++) {
                    if (bytes[i] != undoState.data[i]) {
                        isDifferent = true;
                        break;
                    }
                }
            }

            //Only save undo if the data was different from the last saved undo
            if (isDifferent) {
                //This flag is set to true so we can detect if the object has been reverted
                undoState.hasBeenReverted = true;

                Undo.RegisterUndo (undoState,"A* inspector");

                //Assign the new data
                undoState.data = bytes;

                //Undo.SetSnapshotTarget(undoState,"A* inspector");
                //Undo.CreateSnapshot ();
                //Undo.RegisterSnapshot();

                undoState.hasBeenReverted = false;
                Debug.Log ("Saved "+bytes.Length+" bytes");
                stopWatch.Stop();
                Debug.Log ("Adding Undo "+stopWatch.Elapsed.ToString ());
            }

        }
    }*/
    /** Returns a byte array with the settings of the graph. This function serializes the graph's settings and stores them in a byte array, used for undo operations. This will not save any additional metadata such as which A* version we are working on. */
    private byte[] GetSerializedBytes(NavGraph target)
    {
        //Serialize the settings of the graph
        AstarSerializer sz = new AstarSerializer (editor.script);
        sz.OpenSerialize ();
        sz.SerializeSettings (target,AstarPath.active);
        sz.Close ();
        byte[] bytes = (sz.writerStream.BaseStream as System.IO.MemoryStream).ToArray ();

        return bytes;
    }
コード例 #32
0
 public void SerializeSettings(NavGraph target, AstarSerializer serializer)
 {
     serializer.AddValue("pivot", (int)pivot);
     serializer.AddValue("locked", locked);
     serializer.AddValue("showExtra", showExtra);
 }
コード例 #33
0
    public override void OnInspectorGUI(NavGraph target)
    {
        GridGraph graph = target as GridGraph;

        //GUILayout.BeginHorizontal ();
        //GUILayout.BeginVertical ();
        Rect lockRect;
        Rect tmpLockRect;

        GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle("GridSizeLock");

        if (lockStyle == null)
        {
            lockStyle = new GUIStyle();
        }

        bool sizeSelected1 = false;
        bool sizeSelected2 = false;

#if UNITY_4
        int newWidth = IntField(new GUIContent("Width (nodes)", "Width of the graph in nodes"), graph.width, 100, 0, out lockRect, out sizeSelected1);
        int newDepth = IntField(new GUIContent("Depth (nodes)", "Depth (or height you might also call it) of the graph in nodes"), graph.depth, 100, 0, out tmpLockRect, out sizeSelected2);
#else
        int newWidth = IntField(new GUIContent("Width (nodes)", "Width of the graph in nodes"), graph.width, 50, 0, out lockRect, out sizeSelected1);
        int newDepth = IntField(new GUIContent("Depth (nodes)", "Depth (or height you might also call it) of the graph in nodes"), graph.depth, 50, 0, out tmpLockRect, out sizeSelected2);
#endif

        //Rect r = GUILayoutUtility.GetRect (0,0,lockStyle);

        lockRect.width  = lockStyle.fixedWidth;
        lockRect.height = lockStyle.fixedHeight;
        lockRect.x     += lockStyle.margin.left;
        lockRect.y     += lockStyle.margin.top;

        locked = GUI.Toggle(lockRect, locked, new GUIContent("", "If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"), lockStyle);

        //GUILayout.EndHorizontal ();

        if (newWidth != graph.width || newDepth != graph.depth)
        {
            SnapSizeToNodes(newWidth, newDepth, graph);
        }

        GUI.SetNextControlName("NodeSize");
        newNodeSize = EditorGUILayout.FloatField(new GUIContent("Node size", "The size of a single node. The size is the side of the node square in world units"), graph.nodeSize);

        newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize;

        float prevRatio = graph.aspectRatio;
        graph.aspectRatio = EditorGUILayout.FloatField(new GUIContent("Aspect Ratio", "Scaling of the nodes width/depth ratio. Good for isometric games"), graph.aspectRatio);


        //if ((GUI.GetNameOfFocusedControl () != "NodeSize" && Event.current.type == EventType.Repaint) || Event.current.keyCode == KeyCode.Return) {

        //Debug.Log ("Node Size Not Selected " + Event.current.type);

        if (graph.nodeSize != newNodeSize || prevRatio != graph.aspectRatio)
        {
            if (!locked)
            {
                graph.nodeSize = newNodeSize;
                Matrix4x4 oldMatrix = graph.matrix;
                graph.GenerateMatrix();
                if (graph.matrix != oldMatrix)
                {
                    //Rescann the graphs
                    //AstarPath.active.AutoScan ();
                    GUI.changed = true;
                }
            }
            else
            {
                float delta = newNodeSize / graph.nodeSize;
                graph.nodeSize      = newNodeSize;
                graph.unclampedSize = new Vector2(newWidth * graph.nodeSize, newDepth * graph.nodeSize);
                Vector3 newCenter = graph.matrix.MultiplyPoint3x4(new Vector3((newWidth / 2F) * delta, 0, (newDepth / 2F) * delta));
                graph.center = newCenter;
                graph.GenerateMatrix();

                //Make sure the width & depths stay the same
                graph.width = newWidth;
                graph.depth = newDepth;
                AstarPath.active.AutoScan();
            }
        }
        //}

        Vector3 pivotPoint;
        Vector3 diff;

        EditorGUIUtility.LookLikeControls();
#if !UNITY_4
        EditorGUILayoutx.BeginIndent();
#else
        GUILayout.BeginHorizontal();
#endif

        switch (pivot)
        {
        case GridPivot.Center:
            graph.center = EditorGUILayout.Vector3Field("Center", graph.center);
            break;

        case GridPivot.TopLeft:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(0, 0, graph.depth));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Top-Left", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.TopRight:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(graph.width, 0, graph.depth));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Top-Right", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.BottomLeft:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(0, 0, 0));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Bottom-Left", pivotPoint);
            graph.center = pivotPoint - diff;
            break;

        case GridPivot.BottomRight:
            pivotPoint   = graph.matrix.MultiplyPoint3x4(new Vector3(graph.width, 0, 0));
            diff         = pivotPoint - graph.center;
            pivotPoint   = EditorGUILayout.Vector3Field("Bottom-Right", pivotPoint);
            graph.center = pivotPoint - diff;
            break;
        }

        graph.GenerateMatrix();

        pivot = PivotPointSelector(pivot);

#if !UNITY_4
        EditorGUILayoutx.EndIndent();

        EditorGUILayoutx.BeginIndent();
#else
        GUILayout.EndHorizontal();
#endif

        graph.rotation = EditorGUILayout.Vector3Field("Rotation", graph.rotation);
        //Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector)
        GUILayout.Space(19 + 7);
        //GUILayout.EndHorizontal ();

#if !UNITY_4
        EditorGUILayoutx.EndIndent();
#endif
        EditorGUIUtility.LookLikeInspector();

        if (GUILayout.Button(new GUIContent("Snap Size", "Snap the size to exactly fit nodes"), GUILayout.MaxWidth(100), GUILayout.MaxHeight(16)))
        {
            SnapSizeToNodes(newWidth, newDepth, graph);
        }

        Separator();

        graph.cutCorners = EditorGUILayout.Toggle(new GUIContent("Cut Corners", "Enables or disables cutting corners. See docs for image example"), graph.cutCorners);
        graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup(new GUIContent("Connections", "Sets how many connections a node should have to it's neighbour nodes."), graph.neighbours);

        //GUILayout.BeginHorizontal ();
        //EditorGUILayout.PrefixLabel ("Max Climb");
        graph.maxClimb = EditorGUILayout.FloatField(new GUIContent("Max Climb", "How high, relative to the graph, should a climbable level be. A zero (0) indicates infinity"), graph.maxClimb);
        EditorGUI.indentLevel++;
        graph.maxClimbAxis = EditorGUILayout.IntPopup(new GUIContent("Climb Axis", "Determines which axis the above setting should test on"), graph.maxClimbAxis, new GUIContent[3] {
            new GUIContent("X"), new GUIContent("Y"), new GUIContent("Z")
        }, new int[3] {
            0, 1, 2
        });

        EditorGUI.indentLevel--;
        //GUILayout.EndHorizontal ();

        graph.maxSlope = EditorGUILayout.Slider(new GUIContent("Max Slope", "Sets the max slope in degrees for a point to be walkable. Only enabled if Height Testing is enabled."), graph.maxSlope, 0, 90F);

        graph.erodeIterations = EditorGUILayout.IntField(new GUIContent("Erode iterations", "Sets how many times the graph should be eroded. This adds extra margin to objects. This will not work when using Graph Updates, so if you can, use the Diameter setting in collision settings instead"), graph.erodeIterations);
        graph.erodeIterations = graph.erodeIterations > 16 ? 16 : graph.erodeIterations;         //Clamp iterations to 16

        graph.erosionUseTags = EditorGUILayout.Toggle(new GUIContent("Erosion Uses Tags", "Instead of making nodes unwalkable, " +
                                                                     "nodes will have their tag set to a value corresponding to their erosion level, " +
                                                                     "which is a quite good measurement of their distance to the closest wall."),
                                                      graph.erosionUseTags);
        if (graph.erosionUseTags)
        {
            EditorGUI.indentLevel++;
            graph.erosionFirstTag = EditorGUILayoutx.SingleTagField("First Tag", graph.erosionFirstTag);
            EditorGUI.indentLevel--;
        }

        DrawCollisionEditor(graph.collision);

        Separator();

        showExtra = EditorGUILayout.Foldout(showExtra, "Extra");

        if (showExtra)
        {
            EditorGUI.indentLevel += 2;

            graph.penaltyAngle = ToggleGroup(new GUIContent("Angle Penalty", "Adds a penalty based on the slope of the node"), graph.penaltyAngle);
            //bool preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyAngle && GUI.enabled;
            if (graph.penaltyAngle)
            {
                EditorGUI.indentLevel++;
                graph.penaltyAngleFactor = EditorGUILayout.FloatField(new GUIContent("Factor", "Scale of the penalty. A negative value should not be used"), graph.penaltyAngleFactor);
                //GUI.enabled = preGUI;
                HelpBox("Applies penalty to nodes based on the angle of the hit surface during the Height Testing");

                EditorGUI.indentLevel--;
            }

            graph.penaltyPosition = ToggleGroup("Position Penalty", graph.penaltyPosition);
            //EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition);
            //preGUI = GUI.enabled;
            //GUI.enabled = graph.penaltyPosition && GUI.enabled;
            if (graph.penaltyPosition)
            {
                EditorGUI.indentLevel++;
                graph.penaltyPositionOffset = EditorGUILayout.FloatField("Offset", graph.penaltyPositionOffset);
                graph.penaltyPositionFactor = EditorGUILayout.FloatField("Factor", graph.penaltyPositionFactor);
                HelpBox("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first (" + Int3.Precision + ")\n" +
                        "Be very careful when using negative values since a negative penalty will underflow and instead get really high");
                //GUI.enabled = preGUI;
                EditorGUI.indentLevel--;
            }

            if (textureVisible)
            {
                DrawTextureData(graph.textureData, graph);
            }
            EditorGUI.indentLevel -= 2;
        }
    }
コード例 #34
0
	public bool DrawGraph (NavGraph graph, GraphEditor graphEditor) {
		
		Color tmp1 = GUI.color;
		EditorGUILayoutx.FadeArea topFadeArea = GUILayoutx.BeginFadeArea (graph.open,"","graph_"+graph.guid,graphBoxStyle);


		Color tmp2 = GUI.color;
		GUI.color = tmp1;
		
		GUILayout.BeginHorizontal ();
		string graphNameControl = "graph_"+graph.guid+"_name";
		if (graph.name == null) graph.name = graphEditorTypes[graph.GetType ().Name].displayName;
		
		GUI.SetNextControlName (graphNameControl);
		graph.name = GUILayout.TextField (graph.name, EditorGUILayoutx.defaultLabelStyle, GUILayout.ExpandWidth(false),GUILayout.ExpandHeight(false));
		
		if (graph.name == "" && Event.current.type == EventType.Repaint && GUI.GetNameOfFocusedControl() != graphNameControl) {
			graph.name = graphEditorTypes[graph.GetType ().Name].displayName;
		}
		
		if (GUILayout.Button ("",EditorGUILayoutx.defaultLabelStyle)) {
			graph.open = !graph.open;
			if (!graph.open) {
				graph.infoScreenOpen = false;
			}
			RepaintSceneView ();
			return true;
		}
		
		if (script.prioritizeGraphs) {
			if (GUILayout.Button (new GUIContent ("Up","Increase the graph priority"),GUILayout.Width (40))) {
				int index = script.astarData.GetGraphIndex (graph);
				
				//Find the next non null graph
				int next = index-1;
				for (;next >= 0;next--) if (script.graphs[next] != null) break;
				
				if (next >= 0) {
					NavGraph tmp = script.graphs[next];
					script.graphs[next] = graph;
					script.graphs[index] = tmp;
					
					GraphEditor tmpEditor = graphEditors[next];
					graphEditors[next] = graphEditors[index];
					graphEditors[index] = tmpEditor;
				}
				CheckGraphEditors ();
				Repaint ();
			}
			if (GUILayout.Button (new GUIContent ("Down","Decrease the graph priority"),GUILayout.Width (40))) {
				int index = script.astarData.GetGraphIndex (graph);
				
				//Find the next non null graph
				int next = index+1;
				for (;next<script.graphs.Length;next++) if (script.graphs[next] != null) break;
				
				if (next < script.graphs.Length) {
					NavGraph tmp = script.graphs[next];
					script.graphs[next] = graph;
					script.graphs[index] = tmp;
					
					GraphEditor tmpEditor = graphEditors[next];
					graphEditors[next] = graphEditors[index];
					graphEditors[index] = tmpEditor;
				}
				CheckGraphEditors ();
				Repaint ();
			}
		}
		
		bool drawGizmos = GUILayout.Toggle (graph.drawGizmos,"Draw Gizmos",graphGizmoButtonStyle);
		if (drawGizmos != graph.drawGizmos) {
			graph.drawGizmos = drawGizmos;
			RepaintSceneView ();
		}
		
		if (GUILayout.Toggle (graph.infoScreenOpen,"Info",graphInfoButtonStyle)) {
			if (!graph.infoScreenOpen) {
				graph.infoScreenOpen = true;
				graph.open = true;
			}
		} else {
			graph.infoScreenOpen = false;
		}
		
		if (GUILayout.Button ("Delete",graphDeleteButtonStyle)) {
			RemoveGraph (graph);
			return true;
		}
		GUILayout.EndHorizontal ();


		if (topFadeArea.Show () ) {
			EditorGUILayoutx.FadeArea fadeArea = GUILayoutx.BeginFadeArea (graph.infoScreenOpen,"graph_info_"+graph.guid,0);
			if (fadeArea.Show ()) {
				
				bool nodenull = false;
				int total = 0;
				int numWalkable = 0;

				KeyValuePair<float,KeyValuePair<int,int>> pair;
				if ( graphNodeCounts == null ) graphNodeCounts = new Dictionary<NavGraph, KeyValuePair<float, KeyValuePair<int, int>>>();

				if ( !graphNodeCounts.TryGetValue ( graph, out pair ) || (Time.realtimeSinceStartup-pair.Key) > 2 ) {
					GraphNodeDelegateCancelable counter = delegate (GraphNode node) {
						if (node == null) {
							nodenull = true;
							return true;
						}
						total++;
						if (node.Walkable) numWalkable++;
						return true;
					};
					graph.GetNodes (counter);
					pair = new KeyValuePair<float, KeyValuePair<int, int>> (Time.realtimeSinceStartup, new KeyValuePair<int,int>( total, numWalkable ) );
					graphNodeCounts[graph] = pair;
				}

				total = pair.Value.Key;
				numWalkable = pair.Value.Value;

			
				EditorGUI.indentLevel++;
				
				if (nodenull) {
					//EditorGUILayout.HelpBox ("Some nodes in the graph are null. Please report this error.", MessageType.Info);
					Debug.LogError ("Some nodes in the graph are null. Please report this error.");
				}
				
				EditorGUILayout.LabelField ("Nodes",total.ToString());
				EditorGUILayout.LabelField ("Walkable",numWalkable.ToString ());
				EditorGUILayout.LabelField ("Unwalkable",(total-numWalkable).ToString ());
				if (total == 0) EditorGUILayout.HelpBox ("The number of nodes in the graph is zero. The graph might not be scanned",MessageType.Info);
				
				EditorGUI.indentLevel--;
			}
			GUILayoutx.EndFadeArea ();
			
			GUI.color = tmp2;
			
			graphEditor.OnInspectorGUI (graph);
			graphEditor.OnBaseInspectorGUI (graph);
		}

		GUILayoutx.EndFadeArea ();
		
		return false;
	}
コード例 #35
0
ファイル: RVONavmesh.cs プロジェクト: isoundy000/wzry-1
 public void AddGraphObstacles(Simulator sim, NavGraph graph)
 {
コード例 #36
0
ファイル: Navigation.cs プロジェクト: uk959595/LlamaLibrary
        public static async Task <bool> GetTo(uint ZoneId, Vector3 XYZ)
        {
            /*if (ZoneId == 620)
             * {
             *  var AE = WorldManager.AetheryteIdsForZone(ZoneId).OrderBy(i => i.Item2.DistanceSqr(XYZ)).First();
             *  //LogCritical("Can teleport to AE");
             *  WorldManager.TeleportById(AE.Item1);
             *  await Coroutine.Wait(20000, () => WorldManager.ZoneId == AE.Item1);
             *  await Coroutine.Sleep(2000);
             *  return await FlightorMove(XYZ);
             * }*/

            if (ZoneId == 401 && WorldManager.ZoneId == ZoneId)
            {
                return(await FlightorMove(XYZ));
            }
            var path = await GenerateNodes(ZoneId, XYZ);

            if (ZoneId == 399 && path == null && WorldManager.ZoneId != ZoneId)
            {
                await GetToMap399();
            }

            if (path == null && WorldManager.ZoneId != ZoneId)
            {
                if (WorldManager.AetheryteIdsForZone(ZoneId).Length >= 1)
                {
                    var AE = WorldManager.AetheryteIdsForZone(ZoneId).OrderBy(i => i.Item2.DistanceSqr(XYZ)).First();
                    //LogCritical("Can teleport to AE");
                    WorldManager.TeleportById(AE.Item1);
                    await Coroutine.Wait(20000, () => WorldManager.ZoneId == AE.Item1);

                    await Coroutine.Sleep(2000);

                    return(await GetTo(ZoneId, XYZ));
                }
                else
                {
                    return(false);
                }
            }

            if (path == null)
            {
                bool result = await FlightorMove(XYZ);

                Navigator.Stop();
                return(result);
            }

            if (path.Count < 1)
            {
                LogCritical($"Couldn't get a path to {XYZ} on {ZoneId}, Stopping.");
                return(false);
            }

            object object_0  = new object();
            var    composite = NavGraph.NavGraphConsumer(j => path);

            while (path.Count > 0)
            {
                composite.Start(object_0);
                await Coroutine.Yield();

                while (composite.Tick(object_0) == RunStatus.Running)
                {
                    await Coroutine.Yield();
                }
                composite.Stop(object_0);
                await Coroutine.Yield();
            }

            Navigator.Stop();

            return(Navigator.InPosition(Core.Me.Location, XYZ, 3));
        }
コード例 #37
0
        private byte[] SerializeNodes(int index)
        {
            NavGraph     graph  = graphs[index];
            MemoryStream str    = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(str);

            Node[] nodes = graph.nodes;

            if (nodes == null)
            {
                nodes = new Node[0];
            }

            //Write basic node data.
            //Divide in to different chunks to possibly yield better compression rates with zip
            //The integers above each chunk is a tag to identify each chunk to be able to load them correctly

            writer.Write(1);
            for (int i = 0; i < nodes.Length; i++)
            {
                Node node = nodes[i];
                if (node == null)
                {
                    writer.Write(0);
                    writer.Write(0);
                    writer.Write(0);
                }
                else
                {
                    writer.Write(node.position.x);
                    writer.Write(node.position.y);
                    writer.Write(node.position.z);
                }
            }

            writer.Write(2);
            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] == null)
                {
                    writer.Write(0);
                }
                else
                {
                    writer.Write(nodes[i].penalty);
                }
            }

            writer.Write(3);
            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] == null)
                {
                    writer.Write(0);
                }
                else
                {
                    writer.Write(nodes[i].flags);
                }
            }

            writer.Close();
            return(str.ToArray());
        }
コード例 #38
0
ファイル: Navigation.cs プロジェクト: uk959595/LlamaLibrary
 internal static async Task <Queue <NavGraph.INode> > GenerateNodes(uint ZoneId, Vector3 xyz)
 {
     return(await NavGraph.GetPathAsync((uint)ZoneId, xyz));
 }
コード例 #39
0
	public void RemoveGraph (NavGraph graph) {
		GUILayoutx.RemoveID ("graph_"+graph.guid);
		script.astarData.RemoveGraph (graph);
		CheckGraphEditors ();
		GUI.changed = true;
		Repaint ();
	}
コード例 #40
0
        /**
         * Returns the nearest node to a position using the specified NNConstraint.
         * Searches through all graphs for their nearest nodes to the specified position and picks the closest one.
         * The NNConstraint can be used to specify constraints on which nodes can be chosen such as only picking walkable nodes.
         * \see Pathfinding.NNConstraint
         */
        public static NNInfo GetNearest(Vector3 position, NNConstraint constraint, GraphNode hint)
        {
            // Cache property lookup
            var localGraphs = GetConfig().graphs;

            float          minDist      = float.PositiveInfinity;
            NNInfoInternal nearestNode  = new NNInfoInternal();
            int            nearestGraph = -1;

            if (localGraphs != null)
            {
                for (int i = 0; i < localGraphs.Length; i++)
                {
                    NavGraph graph = localGraphs[i];

                    // Check if this graph should be searched
                    if (graph == null || !constraint.SuitableGraph(i, graph))
                    {
                        continue;
                    }

                    NNInfoInternal nnInfo;
                    if (GetConfig().fullGetNearestSearch)
                    {
                        // Slower nearest node search
                        // this will try to find a node which is suitable according to the constraint
                        nnInfo = graph.GetNearestForce(position, constraint);
                    }
                    else
                    {
                        // Fast nearest node search
                        // just find a node close to the position without using the constraint that much
                        // (unless that comes essentially 'for free')
                        nnInfo = graph.GetNearest(position, constraint);
                    }

                    GraphNode node = nnInfo.node;

                    // No node found in this graph
                    if (node == null)
                    {
                        continue;
                    }

                    // Distance to the closest point on the node from the requested position
                    float dist = ((Vector3)nnInfo.clampedPosition - position).magnitude;

                    if (GetConfig().prioritizeGraphs&& dist < GetConfig().prioritizeGraphsLimit)
                    {
                        // The node is close enough, choose this graph and discard all others
                        minDist      = dist;
                        nearestNode  = nnInfo;
                        nearestGraph = i;
                        break;
                    }
                    else
                    {
                        // Choose the best node found so far
                        if (dist < minDist)
                        {
                            minDist      = dist;
                            nearestNode  = nnInfo;
                            nearestGraph = i;
                        }
                    }
                }
            }

            // No matches found
            if (nearestGraph == -1)
            {
                return(new NNInfo());
            }

            // Check if a constrained node has already been set
            if (nearestNode.constrainedNode != null)
            {
                nearestNode.node            = nearestNode.constrainedNode;
                nearestNode.clampedPosition = nearestNode.constClampedPosition;
            }

            if (!GetConfig().fullGetNearestSearch&& nearestNode.node != null && !constraint.Suitable(nearestNode.node))
            {
                // Otherwise, perform a check to force the graphs to check for a suitable node
                NNInfoInternal nnInfo = localGraphs[nearestGraph].GetNearestForce(position, constraint);

                if (nnInfo.node != null)
                {
                    nearestNode = nnInfo;
                }
            }

            if (!constraint.Suitable(nearestNode.node) || (constraint.constrainDistance &&
                                                           (nearestNode.clampedPosition - position).sqrMagnitude > GetConfig().maxNearestNodeDistanceSqr))
            {
                return(new NNInfo());
            }

            // Convert to NNInfo which doesn't have all the internal fields
            return(new NNInfo(nearestNode));
        }
コード例 #41
0
    //GraphUndo undoState;
    //byte[] savedBytes;
    public override void OnSceneGUI(NavGraph target)
    {
        Event e = Event.current;

        GridGraph graph = target as GridGraph;

        Matrix4x4 matrixPre = graph.matrix;

        graph.GenerateMatrix ();

        if (e.type == EventType.MouseDown) {
            isMouseDown = true;
        } else if (e.type == EventType.MouseUp) {
            isMouseDown = false;
        }

        if (!isMouseDown) {
            savedMatrix = graph.boundsMatrix;
        }

        Handles.matrix = savedMatrix;

        if (graph.nodes == null || (graph.uniformWidhtDepthGrid && graph.depth*graph.width != graph.nodes.Length) || graph.matrix != matrixPre) {
            //Rescann the graphs
            AstarPath.active.AutoScan ();
            //GUI.changed = true;
        }

        Matrix4x4 inversed = savedMatrix.inverse;

        Handles.color = AstarColor.BoundsHandles;

        Handles.DrawCapFunction cap = Handles.CylinderCap;

        Vector2 extents = graph.unclampedSize*0.5F;

        Vector3 center = inversed.MultiplyPoint3x4 (graph.center);

        #if UNITY_3_3
        if (Tools.current == 3) {
        #else
        if (Tools.current == Tool.Scale) {
        #endif

            Vector3 p1 = Handles.Slider (center+new Vector3 (extents.x,0,0),	Vector3.right,		0.1F*HandleUtility.GetHandleSize (center+new Vector3 (extents.x,0,0)),cap,0);
            Vector3 p2 = Handles.Slider (center+new Vector3 (0,0,extents.y),	Vector3.forward,	0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,extents.y)),cap,0);
            //Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0),	Vector3.up,			0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);

            Vector3 p4 = Handles.Slider (center+new Vector3 (-extents.x,0,0),	-Vector3.right,		0.1F*HandleUtility.GetHandleSize (center+new Vector3 (-extents.x,0,0)),cap,0);
            Vector3 p5 = Handles.Slider (center+new Vector3 (0,0,-extents.y),	-Vector3.forward,	0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,-extents.y)),cap,0);

            Vector3 p6 = Handles.Slider (center,	Vector3.up,		0.1F*HandleUtility.GetHandleSize (center),cap,0);

            Vector3 r1 = new Vector3 (p1.x,p6.y,p2.z);
            Vector3 r2 = new Vector3 (p4.x,p6.y,p5.z);

            //Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));

            //if (Tools.viewTool != ViewTool.Orbit) {

                graph.center = savedMatrix.MultiplyPoint3x4 ((r1+r2)/2F);

                Vector3 tmp = r1-r2;
                graph.unclampedSize = new Vector2(tmp.x,tmp.z);

            //}

        #if UNITY_3_3
        } else if (Tools.current == 1) {
        #else
        } else if (Tools.current == Tool.Move) {
        #endif

            if (Tools.pivotRotation == PivotRotation.Local) {
                center = Handles.PositionHandle (center,Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit) {
                    graph.center = savedMatrix.MultiplyPoint3x4 (center);
                }
            } else {
                Handles.matrix = Matrix4x4.identity;

                center = Handles.PositionHandle (graph.center,Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit) {
                    graph.center = center;
                }
            }
        #if UNITY_3_3
        } else if (Tools.current == 2) {
        #else
        } else if (Tools.current == Tool.Rotate) {
        #endif
            //The rotation handle doesn't seem to be able to handle different matrixes of some reason
            Handles.matrix = Matrix4x4.identity;

            Quaternion rot = Handles.RotationHandle (Quaternion.Euler (graph.rotation),graph.center);

            if (Tools.viewTool != ViewTool.Orbit) {
                graph.rotation = rot.eulerAngles;
            }
        }

        //graph.size.x = Mathf.Max (graph.size.x,1);
        //graph.size.y = Mathf.Max (graph.size.y,1);
        //graph.size.z = Mathf.Max (graph.size.z,1);

        Handles.matrix = Matrix4x4.identity;

        }

        public void SerializeSettings (NavGraph target, AstarSerializer serializer) {
        serializer.AddValue ("pivot",(int)pivot);
        serializer.AddValue ("locked",locked);
        serializer.AddValue ("showExtra",showExtra);
        }
コード例 #42
0
ファイル: GridGeneratorEditor.cs プロジェクト: klobodnf/st1
	//GraphUndo undoState;
	//byte[] savedBytes;
	
	public override void OnSceneGUI (NavGraph target) {
		
		Event e = Event.current;
		
		
		
		GridGraph graph = target as GridGraph;
		
		Matrix4x4 matrixPre = graph.matrix;
		
		graph.GenerateMatrix ();
		
		if (e.type == EventType.MouseDown) {
			isMouseDown = true;
		} else if (e.type == EventType.MouseUp) {
			isMouseDown = false;
		}
		
		if (!isMouseDown) {
			savedMatrix = graph.boundsMatrix;
		}
		
		Handles.matrix = savedMatrix;
		
		if (graph.nodes == null || (graph.uniformWidhtDepthGrid && graph.depth*graph.width != graph.nodes.Length) || graph.matrix != matrixPre) {
			//Rescan the graphs
			if (AstarPath.active.AutoScan ()) {
				GUI.changed = true;
			}
		}
		
		Matrix4x4 inversed = savedMatrix.inverse;
		
		Handles.color = AstarColor.BoundsHandles;
		
		Handles.DrawCapFunction cap = Handles.CylinderCap;
		
		Vector2 extents = graph.unclampedSize*0.5F;
		
		Vector3 center = inversed.MultiplyPoint3x4 (graph.center);
		
		
#if UNITY_3_3
		if (Tools.current == 3) {
#else
		if (Tools.current == Tool.Scale) {
#endif
		
			Vector3 p1 = Handles.Slider (center+new Vector3 (extents.x,0,0),	Vector3.right,		0.1F*HandleUtility.GetHandleSize (center+new Vector3 (extents.x,0,0)),cap,0);
			Vector3 p2 = Handles.Slider (center+new Vector3 (0,0,extents.y),	Vector3.forward,	0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,extents.y)),cap,0);
			//Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0),	Vector3.up,			0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);
			
			Vector3 p4 = Handles.Slider (center+new Vector3 (-extents.x,0,0),	-Vector3.right,		0.1F*HandleUtility.GetHandleSize (center+new Vector3 (-extents.x,0,0)),cap,0);
			Vector3 p5 = Handles.Slider (center+new Vector3 (0,0,-extents.y),	-Vector3.forward,	0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,-extents.y)),cap,0);
			
			Vector3 p6 = Handles.Slider (center,	Vector3.up,		0.1F*HandleUtility.GetHandleSize (center),cap,0);
			
			Vector3 r1 = new Vector3 (p1.x,p6.y,p2.z);
			Vector3 r2 = new Vector3 (p4.x,p6.y,p5.z);
			
			//Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));
			
			//if (Tools.viewTool != ViewTool.Orbit) {
			
				graph.center = savedMatrix.MultiplyPoint3x4 ((r1+r2)/2F);
				
				Vector3 tmp = r1-r2;
				graph.unclampedSize = new Vector2(tmp.x,tmp.z);
				
			//}		
		
#if UNITY_3_3
		} else if (Tools.current == 1) {
#else
		} else if (Tools.current == Tool.Move) {
#endif
			
			if (Tools.pivotRotation == PivotRotation.Local) {	
				center = Handles.PositionHandle (center,Quaternion.identity);
				
				if (Tools.viewTool != ViewTool.Orbit) {
					graph.center = savedMatrix.MultiplyPoint3x4 (center);
				}
			} else {
				Handles.matrix = Matrix4x4.identity;
				
				center = Handles.PositionHandle (graph.center,Quaternion.identity);
				
				if (Tools.viewTool != ViewTool.Orbit) {
					graph.center = center;
				}
			}
#if UNITY_3_3
		} else if (Tools.current == 2) {
#else
		} else if (Tools.current == Tool.Rotate) {
#endif
			//The rotation handle doesn't seem to be able to handle different matrixes of some reason
			Handles.matrix = Matrix4x4.identity;
			
			Quaternion rot = Handles.RotationHandle (Quaternion.Euler (graph.rotation),graph.center);
			
			if (Tools.viewTool != ViewTool.Orbit) {
				graph.rotation = rot.eulerAngles;
			}
		}
		
		//graph.size.x = Mathf.Max (graph.size.x,1);
		//graph.size.y = Mathf.Max (graph.size.y,1);
		//graph.size.z = Mathf.Max (graph.size.z,1);
		
		Handles.matrix = Matrix4x4.identity;
		
		
		
#if ASTARDEBUG
		//Draws some info over the node closest to the mouse
		Ray ray = HandleUtility.GUIPointToWorldRay (Event.current.mousePosition);
		
		Vector3 p = ray.GetPoint (100);
		
		
		if (Event.current.shift) {
			
			Node close = graph.GetNearest (p).node;
			
			if (close != null) {
				node1 = close;
			}
				
			if (node1 == null) {
				return;
			}
			
			Handles.SphereCap (0,(Vector3)node1.position,Quaternion.identity,graph.nodeSize*0.5F);
			
			
			//Node node = node1;
			
			GUI.color = Color.white;
			//Handles.Label((Vector3)node.position + Vector3.up*2,"G : "+node.+"\nH : "+node.h+"\nF : "+node.f+"\nPosition : "+node.position.ToString (),EditorStyles.whiteBoldLabel);
		}
		
#endif
		
	}
	
	
	public void SerializeSettings (NavGraph target, AstarSerializer serializer) {
		serializer.AddValue ("pivot",(int)pivot);
		serializer.AddValue ("locked",locked);
		serializer.AddValue ("showExtra",showExtra);
	}
コード例 #43
0
        public void DeSerializeSettings (NavGraph target, AstarSerializer serializer) {
        pivot = (GridPivot)serializer.GetValue ("pivot",typeof(int),GridPivot.BottomLeft);
        locked = (bool)serializer.GetValue ("locked",typeof(bool),true);
        showExtra = (bool)serializer.GetValue ("showExtra",typeof(bool));

        }
コード例 #44
0
    //GraphUndo undoState;
    //byte[] savedBytes;

    public override void OnSceneGUI(NavGraph target)
    {
        Event e = Event.current;



        GridGraph graph = target as GridGraph;

        Matrix4x4 matrixPre = graph.matrix;

        graph.GenerateMatrix();

        if (e.type == EventType.MouseDown)
        {
            isMouseDown = true;
        }
        else if (e.type == EventType.MouseUp)
        {
            isMouseDown = false;
        }

        if (!isMouseDown)
        {
            savedMatrix = graph.boundsMatrix;
        }

        Handles.matrix = savedMatrix;

        if (graph.nodes == null || (graph.uniformWidhtDepthGrid && graph.depth * graph.width != graph.nodes.Length) || graph.matrix != matrixPre)
        {
            //Rescan the graphs
            if (AstarPath.active.AutoScan())
            {
                GUI.changed = true;
            }
        }

        Matrix4x4 inversed = savedMatrix.inverse;

        Handles.color = AstarColor.BoundsHandles;

        Handles.DrawCapFunction cap = Handles.CylinderCap;

        Vector2 extents = graph.unclampedSize * 0.5F;

        Vector3 center = inversed.MultiplyPoint3x4(graph.center);


#if UNITY_3_3
        if (Tools.current == 3)
        {
#else
        if (Tools.current == Tool.Scale)
        {
#endif

            Vector3 p1 = Handles.Slider(center + new Vector3(extents.x, 0, 0), Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(extents.x, 0, 0)), cap, 0);
            Vector3 p2 = Handles.Slider(center + new Vector3(0, 0, extents.y), Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, extents.y)), cap, 0);
            //Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0),	Vector3.up,			0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);

            Vector3 p4 = Handles.Slider(center + new Vector3(-extents.x, 0, 0), -Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(-extents.x, 0, 0)), cap, 0);
            Vector3 p5 = Handles.Slider(center + new Vector3(0, 0, -extents.y), -Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, -extents.y)), cap, 0);

            Vector3 p6 = Handles.Slider(center, Vector3.up, 0.1F * HandleUtility.GetHandleSize(center), cap, 0);

            Vector3 r1 = new Vector3(p1.x, p6.y, p2.z);
            Vector3 r2 = new Vector3(p4.x, p6.y, p5.z);

            //Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));

            //if (Tools.viewTool != ViewTool.Orbit) {

            graph.center = savedMatrix.MultiplyPoint3x4((r1 + r2) / 2F);

            Vector3 tmp = r1 - r2;
            graph.unclampedSize = new Vector2(tmp.x, tmp.z);

            //}

#if UNITY_3_3
        }
        else if (Tools.current == 1)
        {
#else
        }
        else if (Tools.current == Tool.Move)
        {
#endif

            if (Tools.pivotRotation == PivotRotation.Local)
            {
                center = Handles.PositionHandle(center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = savedMatrix.MultiplyPoint3x4(center);
                }
            }
            else
            {
                Handles.matrix = Matrix4x4.identity;

                center = Handles.PositionHandle(graph.center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = center;
                }
            }
#if UNITY_3_3
        }
        else if (Tools.current == 2)
        {
#else
        }
        else if (Tools.current == Tool.Rotate)
        {
#endif
            //The rotation handle doesn't seem to be able to handle different matrixes of some reason
            Handles.matrix = Matrix4x4.identity;

            Quaternion rot = Handles.RotationHandle(Quaternion.Euler(graph.rotation), graph.center);

            if (Tools.viewTool != ViewTool.Orbit)
            {
                graph.rotation = rot.eulerAngles;
            }
        }

        //graph.size.x = Mathf.Max (graph.size.x,1);
        //graph.size.y = Mathf.Max (graph.size.y,1);
        //graph.size.z = Mathf.Max (graph.size.z,1);

        Handles.matrix = Matrix4x4.identity;
    }
コード例 #45
0
    //GraphUndo undoState;
    //byte[] savedBytes;

    public override void OnSceneGUI(NavGraph target)
    {
        Event e = Event.current;



        GridGraph graph = target as GridGraph;

        Matrix4x4 matrixPre = graph.matrix;

        graph.GenerateMatrix();

        if (e.type == EventType.MouseDown)
        {
            isMouseDown = true;
        }
        else if (e.type == EventType.MouseUp)
        {
            isMouseDown = false;
        }

        if (!isMouseDown)
        {
            savedMatrix = graph.boundsMatrix;
        }

        Handles.matrix = savedMatrix;

        if (graph.nodes == null || (graph.uniformWidhtDepthGrid && graph.depth * graph.width != graph.nodes.Length) || graph.matrix != matrixPre)
        {
            //Rescan the graphs
            if (AstarPath.active.AutoScan())
            {
                GUI.changed = true;
            }
        }

        Matrix4x4 inversed = savedMatrix.inverse;

        Handles.color = AstarColor.BoundsHandles;

        Handles.DrawCapFunction cap = Handles.CylinderCap;

        Vector2 extents = graph.unclampedSize * 0.5F;

        Vector3 center = inversed.MultiplyPoint3x4(graph.center);


#if UNITY_3_3
        if (Tools.current == 3)
        {
#else
        if (Tools.current == Tool.Scale)
        {
#endif

            Vector3 p1 = Handles.Slider(center + new Vector3(extents.x, 0, 0), Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(extents.x, 0, 0)), cap, 0);
            Vector3 p2 = Handles.Slider(center + new Vector3(0, 0, extents.y), Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, extents.y)), cap, 0);
            //Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0),	Vector3.up,			0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);

            Vector3 p4 = Handles.Slider(center + new Vector3(-extents.x, 0, 0), -Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(-extents.x, 0, 0)), cap, 0);
            Vector3 p5 = Handles.Slider(center + new Vector3(0, 0, -extents.y), -Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, -extents.y)), cap, 0);

            Vector3 p6 = Handles.Slider(center, Vector3.up, 0.1F * HandleUtility.GetHandleSize(center), cap, 0);

            Vector3 r1 = new Vector3(p1.x, p6.y, p2.z);
            Vector3 r2 = new Vector3(p4.x, p6.y, p5.z);

            //Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));

            //if (Tools.viewTool != ViewTool.Orbit) {

            graph.center = savedMatrix.MultiplyPoint3x4((r1 + r2) / 2F);

            Vector3 tmp = r1 - r2;
            graph.unclampedSize = new Vector2(tmp.x, tmp.z);

            //}

#if UNITY_3_3
        }
        else if (Tools.current == 1)
        {
#else
        }
        else if (Tools.current == Tool.Move)
        {
#endif

            if (Tools.pivotRotation == PivotRotation.Local)
            {
                center = Handles.PositionHandle(center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = savedMatrix.MultiplyPoint3x4(center);
                }
            }
            else
            {
                Handles.matrix = Matrix4x4.identity;

                center = Handles.PositionHandle(graph.center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = center;
                }
            }
#if UNITY_3_3
        }
        else if (Tools.current == 2)
        {
#else
        }
        else if (Tools.current == Tool.Rotate)
        {
#endif
            //The rotation handle doesn't seem to be able to handle different matrixes of some reason
            Handles.matrix = Matrix4x4.identity;

            Quaternion rot = Handles.RotationHandle(Quaternion.Euler(graph.rotation), graph.center);

            if (Tools.viewTool != ViewTool.Orbit)
            {
                graph.rotation = rot.eulerAngles;
            }
        }

        //graph.size.x = Mathf.Max (graph.size.x,1);
        //graph.size.y = Mathf.Max (graph.size.y,1);
        //graph.size.z = Mathf.Max (graph.size.z,1);

        Handles.matrix = Matrix4x4.identity;



#if ASTARDEBUG
        //Draws some info over the node closest to the mouse
        Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

        Vector3 p = ray.GetPoint(100);


        if (Event.current.shift)
        {
            Node close = graph.GetNearest(p).node;

            if (close != null)
            {
                node1 = close;
            }

            if (node1 == null)
            {
                return;
            }

            Handles.SphereCap(0, (Vector3)node1.position, Quaternion.identity, graph.nodeSize * 0.5F);


            //Node node = node1;

            GUI.color = Color.white;
            //Handles.Label((Vector3)node.position + Vector3.up*2,"G : "+node.+"\nH : "+node.h+"\nF : "+node.f+"\nPosition : "+node.position.ToString (),EditorStyles.whiteBoldLabel);
        }
#endif
    }
コード例 #46
0
        /** Adds obstacles for a graph */
        public void AddGraphObstacles(Pathfinding.RVO.Simulator sim, NavGraph graph)
        {
            if (obstacles.Count > 0 && lastSim != null && lastSim != sim)
            {
                Debug.LogError("Simulator has changed but some old obstacles are still added for the previous simulator. Deleting previous obstacles.");
                RemoveObstacles();
            }

            //Remember which simulator these obstacles were added to
            lastSim = sim;

            INavmesh ng = graph as INavmesh;

            if (ng == null)
            {
                return;
            }

            //Assume less than 20 vertices per node (actually assumes 3, but I will change that some day)
            int[] uses = new int[20];

            ng.GetNodes(delegate(GraphNode _node) {
                TriangleMeshNode node = _node as TriangleMeshNode;

                uses[0] = uses[1] = uses[2] = 0;

                if (node != null)
                {
                    //Find out which edges are shared with other nodes
                    for (int j = 0; j < node.connections.Length; j++)
                    {
                        TriangleMeshNode other = node.connections[j] as TriangleMeshNode;

                        // Not necessarily a TriangleMeshNode
                        if (other != null)
                        {
                            int a = node.SharedEdge(other);
                            if (a != -1)
                            {
                                uses[a] = 1;
                            }
                        }
                    }

                    //Loop through all edges on the node
                    for (int j = 0; j < 3; j++)
                    {
                        //The edge is not shared with any other node
                        //I.e it is an exterior edge on the mesh
                        if (uses[j] == 0)
                        {
                            //The two vertices of the edge
                            Vector3 v1 = (Vector3)node.GetVertex(j);
                            Vector3 v2 = (Vector3)node.GetVertex((j + 1) % node.GetVertexCount());

                            //I think node vertices always should be clockwise, but it's good to be certain

                            /*if (!Polygon.IsClockwise (v1,v2,(Vector3)node.GetVertex((j+2) % node.GetVertexCount()))) {
                             *      Vector3 tmp = v2;
                             *      v2 = v1;
                             *      v1 = tmp;
                             * }*/

                #if ASTARDEBUG
                            Debug.DrawLine(v1, v2, Color.red);
                            Debug.DrawRay(v1, Vector3.up * wallHeight, Color.red);
                #endif

                            //Find out the height of the wall/obstacle we are about to add
                            float height = System.Math.Abs(v1.y - v2.y);
                            height       = System.Math.Max(height, 5);

                            //Add the edge as a line obstacle
                            obstacles.Add(sim.AddObstacle(v1, v2, wallHeight));
                        }
                    }
                }

                return(true);
            });
        }
コード例 #47
0
 public void DeSerializeSettings(NavGraph target, AstarSerializer serializer)
 {
     pivot     = (GridPivot)serializer.GetValue("pivot", typeof(int), GridPivot.BottomLeft);
     locked    = (bool)serializer.GetValue("locked", typeof(bool), true);
     showExtra = (bool)serializer.GetValue("showExtra", typeof(bool));
 }
コード例 #48
0
ファイル: AstarPath.cs プロジェクト: Blightbuster/Green-Hell
    private void RecalculateDebugLimits()
    {
        this.debugFloor = float.PositiveInfinity;
        this.debugRoof  = float.NegativeInfinity;
        bool ignoreSearchTree = !this.showSearchTree || this.debugPathData == null;

        Action <GraphNode> < > 9__0;
        for (int i = 0; i < this.graphs.Length; i++)
        {
            if (this.graphs[i] != null && this.graphs[i].drawGizmos)
            {
                NavGraph           navGraph = this.graphs[i];
                Action <GraphNode> action;
                if ((action = < > 9__0) == null)
                {
                    action = (< > 9__0 = delegate(GraphNode node)
                    {
                        if (ignoreSearchTree || GraphGizmoHelper.InSearchTree(node, this.debugPathData, this.debugPathID))
                        {
                            if (this.debugMode == GraphDebugMode.Penalty)
                            {
                                this.debugFloor = Mathf.Min(this.debugFloor, node.Penalty);
                                this.debugRoof = Mathf.Max(this.debugRoof, node.Penalty);
                                return;
                            }
                            if (this.debugPathData != null)
                            {
                                PathNode pathNode = this.debugPathData.GetPathNode(node);
                                switch (this.debugMode)
                                {
                                case GraphDebugMode.G:
                                    this.debugFloor = Mathf.Min(this.debugFloor, pathNode.G);
                                    this.debugRoof = Mathf.Max(this.debugRoof, pathNode.G);
                                    return;

                                case GraphDebugMode.H:
                                    this.debugFloor = Mathf.Min(this.debugFloor, pathNode.H);
                                    this.debugRoof = Mathf.Max(this.debugRoof, pathNode.H);
                                    break;

                                case GraphDebugMode.F:
                                    this.debugFloor = Mathf.Min(this.debugFloor, pathNode.F);
                                    this.debugRoof = Mathf.Max(this.debugRoof, pathNode.F);
                                    return;

                                default:
                                    return;
                                }
                            }
                        }
                    });
                }
                navGraph.GetNodes(action);
            }
        }
        if (float.IsInfinity(this.debugFloor))
        {
            this.debugFloor = 0f;
            this.debugRoof  = 1f;
        }
        if (this.debugRoof - this.debugFloor < 1f)
        {
            this.debugRoof += 1f;
        }
    }
コード例 #49
0
ファイル: GraphEditor.cs プロジェクト: jlonardi/igp-DnM
 /** Draws common graph settings */
 public void OnBaseInspectorGUI(NavGraph target)
 {
     int penalty = EditorGUILayout.IntField (new GUIContent ("Initial Penalty","Initial Penalty for nodes in this graph. Set during Scan."),(int)target.initialPenalty);
     if (penalty < 0) penalty = 0;
     target.initialPenalty = (uint)penalty;
 }
コード例 #50
0
	public bool DrawGraph (NavGraph graph, GraphEditor graphEditor) {
		
		Color tmp1 = GUI.color;
		GUILayoutx.BeginFadeArea (graph.open,"","graph_"+graph.guid,graphBoxStyle);
		Color tmp2 = GUI.color;
		GUI.color = tmp1;
		
		GUILayout.BeginHorizontal ();
		string graphNameControl = "graph_"+graph.guid+"_name";
		if (graph.name == null) graph.name = graphEditorTypes[graph.GetType ().Name].displayName;
		
		GUI.SetNextControlName (graphNameControl);
		graph.name = GUILayout.TextField (graph.name, EditorGUILayoutx.defaultLabelStyle, GUILayout.ExpandWidth(false),GUILayout.ExpandHeight(false));
		
		if (graph.name == "" && Event.current.type == EventType.Repaint && GUI.GetNameOfFocusedControl() != graphNameControl) {
			graph.name = graphEditorTypes[graph.GetType ().Name].displayName;
		}
		
		if (GUILayout.Button ("",EditorGUILayoutx.defaultLabelStyle)) {
			graph.open = !graph.open;
			if (!graph.open) {
				graph.infoScreenOpen = false;
			}
			RepaintSceneView ();
			return true;
		}
		
		if (script.prioritizeGraphs) {
			if (GUILayout.Button (new GUIContent ("Up","Increase the graph priority"),GUILayout.Width (40))) {
				int index = script.astarData.GetGraphIndex (graph);
				
				//Find the next non null graph
				int next = index-1;
				for (;next >= 0;next--) if (script.graphs[next] != null) break;
				
				if (next >= 0) {
					NavGraph tmp = script.graphs[next];
					script.graphs[next] = graph;
					script.graphs[index] = tmp;
					
					GraphEditor tmpEditor = graphEditors[next];
					graphEditors[next] = graphEditors[index];
					graphEditors[index] = tmpEditor;
				}
				CheckGraphEditors ();
				Repaint ();
			}
			if (GUILayout.Button (new GUIContent ("Down","Decrease the graph priority"),GUILayout.Width (40))) {
				int index = script.astarData.GetGraphIndex (graph);
				
				//Find the next non null graph
				int next = index+1;
				for (;next<script.graphs.Length;next++) if (script.graphs[next] != null) break;
				
				if (next < script.graphs.Length) {
					NavGraph tmp = script.graphs[next];
					script.graphs[next] = graph;
					script.graphs[index] = tmp;
					
					GraphEditor tmpEditor = graphEditors[next];
					graphEditors[next] = graphEditors[index];
					graphEditors[index] = tmpEditor;
				}
				CheckGraphEditors ();
				Repaint ();
			}
		}
		
		bool drawGizmos = GUILayout.Toggle (graph.drawGizmos,"Draw Gizmos",graphGizmoButtonStyle);
		if (drawGizmos != graph.drawGizmos) {
			graph.drawGizmos = drawGizmos;
			RepaintSceneView ();
		}
		
		if (GUILayout.Toggle (graph.infoScreenOpen,"Info",graphInfoButtonStyle)) {
			if (!graph.infoScreenOpen) {
				graph.infoScreenOpen = true;
				graph.open = true;
			}
		} else {
			graph.infoScreenOpen = false;
		}
		
		if (GUILayout.Button ("Delete",graphDeleteButtonStyle)) {
			RemoveGraph (graph);
			return true;
		}
		GUILayout.EndHorizontal ();
		
		//if (graph.infoScreenOpen) {
			EditorGUILayoutx.FadeArea fadeArea = GUILayoutx.BeginFadeArea (graph.infoScreenOpen,"graph_info_"+graph.guid,0);
			
			if (fadeArea.Show ()) {
				EditorGUILayout.LabelField ("Nodes",graph.nodes == null ? "null" : graph.nodes.Length.ToString ());
				
				int numWalkable = 0;
				
				if (Event.current.type == EventType.Repaint) {
					if (graph.nodes != null) {
						for (int i=0;i<graph.nodes.Length;i++) {
							if (graph.nodes[i] != null && graph.nodes[i].walkable) numWalkable++;
						}
					}
				}
			
				EditorGUI.indentLevel++;
				
				EditorGUILayout.LabelField ("Walkable",graph.nodes != null ? numWalkable.ToString () : "undefined");
				EditorGUILayout.LabelField ("Unwalkable",graph.nodes != null ? (graph.nodes.Length-numWalkable).ToString () : "undefined");
				
				EditorGUI.indentLevel--;
			}
			GUILayoutx.EndFadeArea ();
		//}
		
		GUI.color = tmp2;
		
		graphEditor.OnInspectorGUI (graph);
		graphEditor.OnBaseInspectorGUI (graph);
		
		GUILayoutx.EndFadeArea ();
		
		return false;
	}
コード例 #51
0
ファイル: GraphEditor.cs プロジェクト: jlonardi/igp-DnM
 /** Override to implement scene GUI drawing for the graph */
 public virtual void OnSceneGUI(NavGraph target)
 {
 }
コード例 #52
0
 void Start()
 {
     lowResGraph  = AstarPath.active.graphs[0];
     highResGraph = AstarPath.active.graphs[1];
     sqrRadius    = radiusOfHighRes * radiusOfHighRes;
 }
コード例 #53
0
ファイル: AstarPath.cs プロジェクト: Blightbuster/Green-Hell
    public NNInfo GetNearest(Vector3 position, NNConstraint constraint, GraphNode hint)
    {
        NavGraph[]     graphs         = this.graphs;
        float          num            = float.PositiveInfinity;
        NNInfoInternal nninfoInternal = default(NNInfoInternal);
        int            num2           = -1;

        if (graphs != null)
        {
            for (int i = 0; i < graphs.Length; i++)
            {
                NavGraph navGraph = graphs[i];
                if (navGraph != null && constraint.SuitableGraph(i, navGraph))
                {
                    NNInfoInternal nninfoInternal2;
                    if (this.fullGetNearestSearch)
                    {
                        nninfoInternal2 = navGraph.GetNearestForce(position, constraint);
                    }
                    else
                    {
                        nninfoInternal2 = navGraph.GetNearest(position, constraint);
                    }
                    if (nninfoInternal2.node != null)
                    {
                        float magnitude = (nninfoInternal2.clampedPosition - position).magnitude;
                        if (this.prioritizeGraphs && magnitude < this.prioritizeGraphsLimit)
                        {
                            nninfoInternal = nninfoInternal2;
                            num2           = i;
                            break;
                        }
                        if (magnitude < num)
                        {
                            num            = magnitude;
                            nninfoInternal = nninfoInternal2;
                            num2           = i;
                        }
                    }
                }
            }
        }
        if (num2 == -1)
        {
            return(default(NNInfo));
        }
        if (nninfoInternal.constrainedNode != null)
        {
            nninfoInternal.node            = nninfoInternal.constrainedNode;
            nninfoInternal.clampedPosition = nninfoInternal.constClampedPosition;
        }
        if (!this.fullGetNearestSearch && nninfoInternal.node != null && !constraint.Suitable(nninfoInternal.node))
        {
            NNInfoInternal nearestForce = graphs[num2].GetNearestForce(position, constraint);
            if (nearestForce.node != null)
            {
                nninfoInternal = nearestForce;
            }
        }
        if (!constraint.Suitable(nninfoInternal.node) || (constraint.constrainDistance && (nninfoInternal.clampedPosition - position).sqrMagnitude > this.maxNearestNodeDistanceSqr))
        {
            return(default(NNInfo));
        }
        return(new NNInfo(nninfoInternal));
    }
コード例 #54
0
    //GraphUndo undoState;
    //byte[] savedBytes;

    public override void OnSceneGUI(NavGraph target)
    {
        Event e = Event.current;



        GridGraph graph = target as GridGraph;

        Matrix4x4 matrixPre = graph.matrix;

        graph.GenerateMatrix();

        if (e.type == EventType.MouseDown)
        {
            isMouseDown = true;
        }
        else if (e.type == EventType.MouseUp)
        {
            isMouseDown = false;
        }

        if (!isMouseDown)
        {
            savedMatrix = graph.boundsMatrix;
        }

        Handles.matrix = savedMatrix;

        if (graph.nodes == null || (graph.uniformWidhtDepthGrid && graph.depth * graph.width != graph.nodes.Length) || graph.matrix != matrixPre)
        {
            //Rescann the graphs
            AstarPath.active.AutoScan();
            GUI.changed = true;
        }

        Matrix4x4 inversed = savedMatrix.inverse;

        Handles.color = AstarColor.BoundsHandles;

        Handles.DrawCapFunction cap = Handles.CylinderCap;

        Vector2 extents = graph.unclampedSize * 0.5F;

        //Tools.current is an undocumented editor variable, remove the UseUndocumentedEditorFeatures define at the top of the script to make sure it's forward compatible

        /*if (undoState == null) {
         *      undoState = ScriptableObject.CreateInstance<GraphUndo>();
         * }
         *
         * if (undoState.hasBeenReverted) {
         *      undoState.ApplyUndo (graph);
         *      GUI.changed = true;
         * }*/

        /*if (Event.current.button == 0 && Event.current.isMouse && (/*Event.current.type == EventType.MouseUp || /Event.current.type == EventType.MouseDown)) {
         *      AstarSerializer sz = new AstarSerializer ();
         *      sz.OpenSerializeSettings ();
         *      sz.SerializeSettings (graph,AstarPath.active);
         *      byte[] bytes = (sz.writerStream.BaseStream as System.IO.MemoryStream).ToArray ();
         *      sz.Close ();
         *
         *      undoState.data = bytes;
         *      undoState.hasBeenReverted = true;
         *
         *      Undo.RegisterUndo (undoState,"Graph stuff");
         *      undoState.hasBeenReverted = false;
         *
         * }*/

        //Undo.SetSnapshotTarget (AstarPath.active.astarData,"Change graph");

        Vector3 center = inversed.MultiplyPoint3x4(graph.center);         //Vector3.zero;//inversed.MultiplyPoint3x4 (graph.center);//graph.center;


#if UNITY_3_3
        if (Tools.current == 3)
        {
#else
        if (Tools.current == Tool.Scale)
        {
#endif

            Vector3 p1 = Handles.Slider(center + new Vector3(extents.x, 0, 0), Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(extents.x, 0, 0)), cap, 0);
            Vector3 p2 = Handles.Slider(center + new Vector3(0, 0, extents.y), Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, extents.y)), cap, 0);
            //Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0),	Vector3.up,			0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);

            Vector3 p4 = Handles.Slider(center + new Vector3(-extents.x, 0, 0), -Vector3.right, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(-extents.x, 0, 0)), cap, 0);
            Vector3 p5 = Handles.Slider(center + new Vector3(0, 0, -extents.y), -Vector3.forward, 0.1F * HandleUtility.GetHandleSize(center + new Vector3(0, 0, -extents.y)), cap, 0);

            Vector3 p6 = Handles.Slider(center, Vector3.up, 0.1F * HandleUtility.GetHandleSize(center), cap, 0);

            Vector3 r1 = new Vector3(p1.x, p6.y, p2.z);
            Vector3 r2 = new Vector3(p4.x, p6.y, p5.z);

            //Vector3 min = Vector3.Min (r1,r2);
            //Vector3 max = Vector3.Max (r1,r2);

            /*b.Encapsulate (p1);
            *  b.Encapsulate (p2);
            *  b.Encapsulate (p3);
            *  b.Encapsulate (p4);
            *  b.Encapsulate (p5);
            *  b.Encapsulate (p6);*/

            //Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));

            //if (Tools.viewTool != ViewTool.Orbit) {

            graph.center = savedMatrix.MultiplyPoint3x4((r1 + r2) / 2F);

            Vector3 tmp = r1 - r2;
            graph.unclampedSize = new Vector2(tmp.x, tmp.z);

            //}

#if UNITY_3_3
        }
        else if (Tools.current == 1)
        {
#else
        }
        else if (Tools.current == Tool.Move)
        {
#endif

            if (Tools.pivotRotation == PivotRotation.Local)
            {
                center = Handles.PositionHandle(center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = savedMatrix.MultiplyPoint3x4(center);
                }
            }
            else
            {
                Handles.matrix = Matrix4x4.identity;

                center = Handles.PositionHandle(graph.center, Quaternion.identity);

                if (Tools.viewTool != ViewTool.Orbit)
                {
                    graph.center = center;
                }
            }
#if UNITY_3_3
        }
        else if (Tools.current == 2)
        {
#else
        }
        else if (Tools.current == Tool.Rotate)
        {
#endif
            //The rotation handle doesn't seem to be able to handle different matrixes of some reason
            Handles.matrix = Matrix4x4.identity;

            Quaternion rot = Handles.RotationHandle(Quaternion.Euler(graph.rotation), graph.center);

            if (Tools.viewTool != ViewTool.Orbit)
            {
                graph.rotation = rot.eulerAngles;
            }
        }

        //graph.size.x = Mathf.Max (graph.size.x,1);
        //graph.size.y = Mathf.Max (graph.size.y,1);
        //graph.size.z = Mathf.Max (graph.size.z,1);

        Handles.matrix = Matrix4x4.identity;



        Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

        Vector3 p = ray.GetPoint(100);


        if (Event.current.shift)
        {
            Node close = graph.GetNearest(p);

            if (close != null)
            {
                node1 = close;
            }
        }


        if (node1 == null)
        {
            return;
        }

        Handles.SphereCap(0, node1.position, Quaternion.identity, graph.nodeSize);


        Node node = node1;

        GUI.color = Color.white;
        Handles.Label((Vector3)node.position + Vector3.up * 2, "G : " + node.g + "\nH : " + node.h + "\nF : " + node.f + "\nPosition : " + node.position.ToString(), EditorStyles.whiteBoldLabel);
    }
コード例 #55
0
        /*
         * The important thing to know going into reading this method is that it's not possible to
         * modify the backstack. You can only push and pop to and from the top of the stack.
         * So if a user uses an API like `RemovePage` or `InsertPage` we will typically ignore processing those here
         * unless it requires changes to the NavBar (i.e removing the first page with only 2 pages on the stack).
         * Once the user performs an operation that changes the currently visible page then we process any stack changes
         * that have occurred.
         * Let's say the user has pages A,B,C,D on the stack
         * If they remove Page B and Page C then we don't do anything. Then if the user pushes E onto the stack
         * we just transform A,B,C,D into A,D,E.
         * Platform wise that's a "pop" but we use the correct animation for a "push" so visually it looks like a push.
         * This is also the reason why we aren't using the custom animation features on the navigation component itself.
         * Because we might be popping but visually pushing.
         *
         * The Fragments that are on the stack also do not have a hard connection to the page they originally rendereded.
         * Whenever a fragment is the "visible" fragment it just figures out what the current page is and displays that.
         * Fragments are recreated everytime they are pushed on the stack but the handler renderer is not.
         * It's just attached to a new fragment
         * */
        void ApplyNavigationRequest(NavigationRequest args)
        {
            if (IsNavigating)
            {
                // This should really never fire for the developer. Our xplat code should be handling waiting for navigation to
                // complete before requesting another navigation from Core
                // Maybe some day we'll put a navigation queue into Core? For now we won't
                throw new InvalidOperationException("Previous Navigation Request is still Processing");
            }

            if (args.NavigationStack.Count == 0)
            {
                throw new InvalidOperationException("NavigationStack cannot be empty");
            }

            ActiveRequestedArgs = args;
            IReadOnlyList <IView> newPageStack = args.NavigationStack;
            bool animated                     = args.Animated;
            var  navController                = NavHost.NavController;
            var  previousNavigationStack      = NavigationStack;
            var  previousNavigationStackCount = previousNavigationStack.Count;
            bool initialNavigation            = NavigationStack.Count == 0;

            // This updates the graphs public navigation stack property so it's outwardly correct
            // But we've saved off the previous stack so we can correctly interpret navigation
            UpdateNavigationStack(newPageStack);

            // This indicates that this is the first navigation request so we need to initialize the graph
            if (initialNavigation)
            {
                IsInitialNavigation = true;
                Initialize(args.NavigationStack);
                return;
            }

            // If the new stack isn't changing the visible page or the app bar then we just ignore
            // the changes because there's no point to applying these to the platform back stack
            // We only apply changes when the currently visible page changes and/or the appbar
            // will change (gain a back button)
            if (newPageStack[newPageStack.Count - 1] == previousNavigationStack[previousNavigationStackCount - 1])
            {
                NavigationFinished(NavigationView);

                // There's only one page on the stack then we trigger back button visibility logic
                // so that it can add a back button if it needs to
                if (previousNavigationStackCount == 1 || newPageStack.Count == 1)
                {
                    TriggerBackButtonVisibleUpdate();
                }

                return;
            }

            // The incoming fragment uses these variables to pick the correct animation for the current
            // incoming navigation request
            if (newPageStack[newPageStack.Count - 1] == previousNavigationStack[previousNavigationStackCount - 1])
            {
                IsPopping = null;
            }
            else
            {
                IsPopping = newPageStack.Count < previousNavigationStackCount;
            }

            IsAnimated = animated;

            var iterator = NavHost.NavController.BackQueue.Iterator();
            var fragmentNavDestinations = new List <FragmentNavigator.Destination>();

            while (iterator.HasNext)
            {
                if (iterator.Next() is NavBackStackEntry nbse &&
                    nbse.Destination is FragmentNavigator.Destination nvd)
                {
                    fragmentNavDestinations.Add(nvd);
                }
            }

            // Current BackStack has less entries then incoming new page stack
            // This will add Back Stack Entries until the back stack and the new stack
            // match up
            if (fragmentNavDestinations.Count < newPageStack.Count)
            {
                for (int i = fragmentNavDestinations.Count; i < newPageStack.Count; i++)
                {
                    var dest = AddFragmentDestination();
                    navController.Navigate(dest.Id);
                }
            }
            // User just wants to replace the currently visible page but the number
            // of items in the stack are still the same.
            // In theory we could just prompt the currently active fragment to swap out the new PageView
            // But this way we get an animation
            else if (newPageStack.Count == fragmentNavDestinations.Count)
            {
                int lastFragId = fragmentNavDestinations[newPageStack.Count - 1].Id;
                navController.PopBackStack();
                navController.Navigate(lastFragId);
            }
            // Our back stack has more entries on it then
            else
            {
                int popToId = fragmentNavDestinations[newPageStack.Count - 1].Id;
                navController.PopBackStack(popToId, false);
            }

            // We only keep destinations around that are on the backstack
            // This iterates over the new backstack and removes any destinations
            // that are no longer apart of the back stack
            var iterateNewStack = NavHost.NavController.BackQueue.Iterator();
            int startId         = -1;

            while (iterateNewStack.HasNext)
            {
                if (iterateNewStack.Next() is NavBackStackEntry nbse &&
                    nbse.Destination is FragmentNavigator.Destination nvd)
                {
                    fragmentNavDestinations.Remove(nvd);

                    if (startId == -1)
                    {
                        startId = nvd.Id;
                    }
                }
            }

            foreach (var activeDestinations in fragmentNavDestinations)
            {
                NavGraph.Remove(activeDestinations);
            }

            // If we end up removing the destination that was initially the StartDestination
            // The Navigation Graph can get really confused
            if (NavGraph.StartDestination != startId)
            {
                NavGraph.StartDestination = startId;
            }

            // The NavigationIcon on the toolbar gets set inside the Navigate call so this is the earliest
            // point in time that we can setup toolbar colors for the incoming page
            TriggerBackButtonVisibleUpdate();
        }
コード例 #56
0
	void RemoveGraph (NavGraph graph) {
		guiLayoutx.RemoveID (graph.guid.ToString());
		script.astarData.RemoveGraph (graph);
		CheckGraphEditors ();
		GUI.changed = true;
		Repaint ();
	}
コード例 #57
0
ファイル: RVONavmesh.cs プロジェクト: isoundy000/moba-1
    /** Adds obstacles for a graph */
    public void AddGraphObstacles(Pathfinding.RVO.Simulator sim, NavGraph graph)
    {
        if (obstacles.Count > 0 && lastSim != null && lastSim != sim)
        {
            Debug.LogError("Simulator has changed but some old obstacles are still added for the previous simulator. Deleting previous obstacles.");
            RemoveObstacles();
        }

        //Remember which simulator these obstacles were added to
        lastSim = sim;

        INavmesh ng = graph as INavmesh;

        if (ng == null)
        {
            return;
        }

        Node[] nodes = graph.nodes;

        Int3[] vertices = ng.vertices;

        int[] uses = new int[3];

        for (int i = 0; i < nodes.Length; i++)
        {
            MeshNode node = nodes[i] as MeshNode;

            uses[0] = uses[1] = uses[2] = 0;

            if (node != null)
            {
                for (int j = 0; j < node.connections.Length; j++)
                {
                    MeshNode other = node.connections[j] as MeshNode;
                    if (other == null)
                    {
                        continue;
                    }

                    int first  = -1;
                    int second = -1;

                    for (int x = 0; x < 3; x++)
                    {
                        for (int y = 0; y < 3; y++)
                        {
                            if (node[x] == other[y] && first < 0)
                            {
                                first = x;
                                break;
                            }
                            else if (node[x] == other[y])
                            {
                                second = x;
                                break;
                            }
                        }
                        if (second >= 0)
                        {
                            break;
                        }
                    }

                    //Only shared one vertex
                    if (second == -1)
                    {
                        continue;
                    }

                    if ((first + 1) % 3 == second)
                    {
                        uses[first]++;
                    }
                    else                         //if ((second+1) % 3 == first) {
                    {
                        uses[second]++;
                    }
                }
            }

            for (int j = 0; j < 3; j++)
            {
                if (uses[j] == 0)
                {
                    Vector3 v1 = (Vector3)vertices[node[j]];
                    Vector3 v2 = (Vector3)vertices[node[(j + 1) % 3]];

                    //I think node vertices always should be clockwise, but it's good to be certain
                    if (!Polygon.IsClockwise(v1, v2, (Vector3)vertices[node[(j + 2) % 3]]))
                    {
                        Vector3 tmp = v2;
                        v2 = v1;
                        v1 = tmp;
                    }

#if ASTARDEBUG
                    Debug.DrawLine(v1, v2, Color.red);
                    Debug.DrawRay(v1, Vector3.up * wallHeight, Color.red);
#endif

                    float height = System.Math.Abs(v1.y - v2.y);
                    height = System.Math.Max(height, 5);

                    obstacles.Add(sim.AddObstacle(v1, v2, wallHeight));
                }
            }
        }
    }
コード例 #58
0
ファイル: RVONavmesh.cs プロジェクト: sonygod/ESPUnity
    /** Adds obstacles for a graph */
    public void AddGraphObstacles(Pathfinding.RVO.Simulator sim, NavGraph graph)
    {
        if (obstacles.Count > 0 && lastSim != null && lastSim != sim) {
            Debug.LogError ("Simulator has changed but some old obstacles are still added for the previous simulator. Deleting previous obstacles.");
            RemoveObstacles ();
        }

        //Remember which simulator these obstacles were added to
        lastSim = sim;

        INavmesh ng = graph as INavmesh;

        if (ng == null) return;

        Node[] nodes = graph.nodes;

        Int3[] vertices = ng.vertices;

        int[] uses = new int[3];

        for (int i=0;i<nodes.Length;i++) {
            MeshNode node = nodes[i] as MeshNode;

            uses[0] = uses[1] = uses[2] = 0;

            if (node != null) {

                for (int j=0;j<node.connections.Length;j++) {
                    MeshNode other = node.connections[j] as MeshNode;
                    if (other == null) continue;

                    int first = -1;
                    int second = -1;

                    for (int x=0;x<3;x++) {
                        for (int y=0;y<3;y++) {
                            if (node[x] == other[y] && first < 0) {
                                first = x;
                                break;
                            } else if (node[x] == other[y]) {
                                second = x;
                                break;
                            }
                        }
                        if (second >= 0) break;
                    }

                    //Only shared one vertex
                    if (second == -1) continue;

                    if ((first+1) % 3 == second) {
                        uses[first]++;
                    } else { //if ((second+1) % 3 == first) {
                        uses[second]++;
                    }
                }
            }

            for (int j=0;j<3;j++) {
                if (uses[j] == 0) {
                    Vector3 v1 = (Vector3)vertices[node[j]];
                    Vector3 v2 = (Vector3)vertices[node[(j+1) % 3]];

                    //I think node vertices always should be clockwise, but it's good to be certain
                    if (!Polygon.IsClockwise (v1,v2,(Vector3)vertices[node[(j+2) % 3]])) {
                        Vector3 tmp = v2;
                        v2 = v1;
                        v1 = tmp;
                    }

        #if ASTARDEBUG
                    Debug.DrawLine (v1,v2,Color.red);
                    Debug.DrawRay (v1,Vector3.up*wallHeight,Color.red);
        #endif

                    float height = System.Math.Abs(v1.y-v2.y);
                    height = System.Math.Max (height,5);

                    obstacles.Add (sim.AddObstacle (v1, v2, wallHeight));
                }
            }
        }
    }
コード例 #59
0
        /** Deserializes graph settings.
         * \note Stored in files named "graph#.json" where # is the graph number.
         */
        public NavGraph[] DeserializeGraphs()
        {
            //for (int j=0;j<1;j++) {
            //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            //watch.Start();

            graphs = new NavGraph[meta.graphs];

            int nonNull = 0;

            for (int i = 0; i < meta.graphs; i++)
            {
                Type tp = meta.GetGraphType(i);

                //Graph was null when saving, ignore
                if (System.Type.Equals(tp, null))
                {
                    continue;
                }

                nonNull++;

                ZipEntry entry = zip["graph" + i + jsonExt];

                if (entry == null)
                {
                    throw new FileNotFoundException("Could not find data for graph " + i + " in zip. Entry 'graph+" + i + jsonExt + "' does not exist");
                }


                NavGraph tmp = data.CreateGraph(tp);                //(NavGraph)System.Activator.CreateInstance(tp);

#if !ASTAR_NO_JSON
                String entryText = GetString(entry);

                JsonReader reader = new JsonReader(entryText, readerSettings);

                //NavGraph graph = tmp.Deserialize(reader);//reader.Deserialize<NavGraph>();
                reader.PopulateObject(ref tmp);
#else
                var mem = new MemoryStream();
                entry.Extract(mem);
                mem.Position = 0;
                var reader = new BinaryReader(mem);
                var ctx    = new GraphSerializationContext(reader, null, i);
                tmp.DeserializeSettings(ctx);
#endif

                graphs[i] = tmp;
                if (graphs[i].guid.ToString() != meta.guids[i])
                {
                    throw new System.Exception("Guid in graph file not equal to guid defined in meta file. Have you edited the data manually?\n" + graphs[i].guid.ToString() + " != " + meta.guids[i]);
                }

                //NavGraph graph = (NavGraph)JsonConvert.DeserializeObject (entryText,tp,settings);
            }

            NavGraph[] compressed = new NavGraph[nonNull];
            nonNull = 0;
            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i] != null)
                {
                    compressed[nonNull] = graphs[i];
                    nonNull++;
                }
            }

            graphs = compressed;

            return(graphs);

            //watch.Stop();
            //Debug.Log ((watch.ElapsedTicks*0.0001).ToString ("0.00"));
            //}
        }
コード例 #60
0
    // img width and height
    // By default, C# creates param: para_graph as a new reference to the object. It does not copy the object but it creates a new reference.
    // The ref keyword refers to the same object but prevents duplicating the reference.
    private void includeNode(int para_graphID,
	                         NavGraph para_graph,
	                         int para_nodeX,
	                         int para_nodeY,
	                         Color para_nodeColor,
	                         int[] para_imgWNH)
    {
        // PREP.
        NavGraph retGraph = para_graph;
        GraphTmpMetaData reqGraphMetaData = graphMetaDataArr[para_graphID];
        int c = para_nodeX;
        int r = para_nodeY;
        int nxtNodeID = reqGraphMetaData.nxtNodeID;
        int nxtEdgeID = reqGraphMetaData.nxtEdgeID;
        Dictionary<string,int> coordToNodeIDMap = reqGraphMetaData.coordToNodeIDMap;

        // GO.

        // Add new node.
        WorldNode nwNode = new WorldNode(nxtNodeID,
                                         reqGraphMetaData.colorToNodeType[para_nodeColor],
                                         new Vector3((worldGProp.x + (worldGProp.cellWidth/2f)) + (worldGProp.cellWidth * c),
                                                     (worldGProp.y - (worldGProp.cellWidth/2f)) - (worldGProp.cellHeight * r),
                                                     worldGProp.z));

        retGraph.addNode(nwNode);
        coordToNodeIDMap.Add((""+c+"-"+r),nwNode.getNodeID());
        nxtNodeID++;

        // Get valid neighbourhood pixels.
        List<Color> neighbourhoodPixels = new List<Color>();
        List<int[]> reqNPixCoords = new List<int[]>();

        //reqNPixCoords.Add(new int[2]{(c-1),(r-1)});
        reqNPixCoords.Add(new int[2]{(c),(r-1)});
        //reqNPixCoords.Add(new int[2]{(c+1),(r-1)});
        reqNPixCoords.Add(new int[2]{(c-1),(r)});
        List<int> validCoordIndexList = new List<int>();
        for(int k=0; k<reqNPixCoords.Count; k++)
        {
            int[] tmpCoords = reqNPixCoords[k];

            if((tmpCoords[0] >= 0)&&(tmpCoords[0] < para_imgWNH[0])            // mapImg.width)
               &&(tmpCoords[1] >= 0)&&(tmpCoords[1] < para_imgWNH[1]))		   // mapImg.height))
            {
                // Valid coords.
                validCoordIndexList.Add(k);
                neighbourhoodPixels.Add( pixels[(pixels.Length - para_imgWNH[0]) - (tmpCoords[1] * para_imgWNH[0]) + tmpCoords[0]] );
            }
        }

        // Check for neighbours and create edges. (NavGraph will handle the internal creation of neighbour references, just run addEdge).
        for(int k=0; k<validCoordIndexList.Count; k++)
        {

            if(colourDestinationGraphMap.ContainsKey(neighbourhoodPixels[k]))
            {
                if(colourDestinationGraphMap[neighbourhoodPixels[k]].Contains(para_graphID))
                {
                    int[] neighbourCoords = reqNPixCoords[k];
                    int neighbourID = coordToNodeIDMap[(""+neighbourCoords[0]+"-"+neighbourCoords[1])];

                    retGraph.addEdge(nwNode.getNodeID(),neighbourID,new NavEdge(new int[2] {nwNode.getNodeID(),neighbourID},1));
                }
            }
        }

        // POST.

        reqGraphMetaData.nxtNodeID = nxtNodeID;
        reqGraphMetaData.nxtEdgeID = nxtEdgeID;
        reqGraphMetaData.coordToNodeIDMap = coordToNodeIDMap;
        graphMetaDataArr[para_graphID] = reqGraphMetaData;
    }