Skip to content

Commit

Permalink
Add Serialization Button
Browse files Browse the repository at this point in the history
  • Loading branch information
AkiKurisu committed Sep 5, 2023
1 parent 023884e commit c3c1886
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 87 deletions.
2 changes: 1 addition & 1 deletion Editor/Core/GOAPPlannerProEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class GOAPPlannerProEditor : UnityEditor.Editor
private const string IsActiveTooltip = "Whether current planner is active, will be disbled automatically" +
" when skipSearchWhenActionRunning is on";
private const string SkilSearchTooltip = "Enabled to skip search plan when already have an action, enable this will need you to set correct precondition" +
"for each action to let it quit by itself";
" for each action to let it quit by itself";
public override VisualElement CreateInspectorGUI()
{
var myInspector = new VisualElement();
Expand Down
34 changes: 17 additions & 17 deletions Editor/Core/GOAPPlannerSnapshotEditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ public class GOAPPlannerSnapshotEditorWindow : EditorWindow

private readonly List<PlanCache> planeCaches = new List<PlanCache>();
private int currentIndex;
private List<GoalData> goalData => planeCaches[currentIndex].goalData;
private List<IAction> activePlan => planeCaches[currentIndex].activePlan;
private IGoal activeGoal => planeCaches[currentIndex].activeGoal;
private int activeActionIdx => planeCaches[currentIndex].activeActionIdx;
private List<GoalData> GoalData => planeCaches[currentIndex].goalData;
private List<IAction> ActivePlan => planeCaches[currentIndex].activePlan;
private IGoal ActiveGoal => planeCaches[currentIndex].activeGoal;
private int ActiveActionIdx => planeCaches[currentIndex].activeActionIdx;
private class PlanCache
{
public IGoal activeGoal;
Expand All @@ -64,7 +64,7 @@ private class PlanCache
}
public static void Show(IPlanner planner)
{
var window = GOAPPlannerSnapshotEditorWindow.GetWindow<GOAPPlannerSnapshotEditorWindow>("GOAP Planner Snapshot");
var window = GetWindow<GOAPPlannerSnapshotEditorWindow>("GOAP Planner Snapshot");
window.SetUp(planner);
window.Show();
}
Expand Down Expand Up @@ -159,9 +159,9 @@ private void CachePlan(IPlanner planner)
planeCaches.Add(new PlanCache
{
activeGoal = planner.ActivateGoal,
goalData = (planner as IPlanner).GetSortedGoalData(),
goalData = planner.GetSortedGoalData(),
activePlan = new List<IAction>(planner.ActivatePlan),
activeActionIdx = (planner as IPlanner).ActiveActionIndex
activeActionIdx = planner.ActiveActionIndex
});
if (planeCaches.Count > 50) planeCaches.RemoveAt(0);
}
Expand Down Expand Up @@ -275,17 +275,17 @@ private void DrawGoalPriorities(int unusedWindowID)
GUILayout.Label("\n\n");
GUI.color = runningTint;
GUI.backgroundColor = backgroundNodeColor;
for (int i = 0; i < goalData.Count; i++)
for (int i = 0; i < GoalData.Count; i++)
{
GUI.Box(
new Rect(
0,
30f + i * prioritySpacing,
Mathf.Clamp(goalData[i].priority, 0.05f, 1f) * maxPriorityRectWidth,
Mathf.Clamp(GoalData[i].priority, 0.05f, 1f) * maxPriorityRectWidth,
priorityRectHeight
),
goalData[i].goalName,
goalData[i].canRun ? goalLabelStyle : disabledGoalLabelStyle
GoalData[i].goalName,
GoalData[i].canRun ? goalLabelStyle : disabledGoalLabelStyle
);
}

Expand All @@ -298,7 +298,7 @@ private void DrawActionNodes(int unusedWindowID)
{
if (planeCaches.Count == 0) return;
int count = 0;
for (int i = 0; i < activePlan.Count; i++)
for (int i = 0; i < ActivePlan.Count; i++)
{

// Draw link
Expand All @@ -313,7 +313,7 @@ private void DrawActionNodes(int unusedWindowID)

GUI.color = defaultTint;
GUI.backgroundColor = backgroundNodeColor;
if (i == activeActionIdx)
if (i == ActiveActionIdx)
{
GUI.color = runningTint;
activeNodeStyle = selectedNodeStyle;
Expand All @@ -328,7 +328,7 @@ private void DrawActionNodes(int unusedWindowID)
"",
activeNodeStyle);

actionContent.text = "\nAction\n\n" + activePlan[i].Name;
actionContent.text = "\nAction\n\n" + ActivePlan[i].Name;

// Draw task rect
GUI.backgroundColor = actionColor;
Expand All @@ -353,7 +353,7 @@ private void DrawActionNodes(int unusedWindowID)
"",
selectedNodeStyle);
GUI.backgroundColor = goalColor;
goalContent.text = "\nGoal\n\n" + activeGoal.Name;
goalContent.text = "\nGoal\n\n" + ActiveGoal.Name;
GUI.Box(
GetTaskRect(count),
goalContent,
Expand Down Expand Up @@ -394,12 +394,12 @@ private void DrawLink(
float thickness = 4f)
{

Vector2 startPos = new Vector2(
Vector2 startPos = new(
startGridPos * nodeSpacing.x + nodeSize.x,
activePlanHeight + nodeSize.y * .5f
);

Vector2 endPos = new Vector2(
Vector2 endPos = new(
endGridPos * nodeSpacing.x,
activePlanHeight + nodeSize.y * .5f
);
Expand Down
10 changes: 5 additions & 5 deletions Editor/Node/GOAPActionNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ namespace Kurisu.GOAP.Editor
{
public class GOAPActionNode : GOAPNode
{
public GOAPActionNode():base()
public GOAPActionNode() : base()
{
label.style.color=Color.black;
label.style.color = Color.black;
}
private readonly Label label=new Label();
private readonly Label label = new();
protected sealed override void OnCleanUp()
{
titleContainer.Remove(label);
}
public void SetUp(float cost)
{
style.backgroundColor=Color.green;
label.text=$"Cost : {cost}";
style.backgroundColor = Color.green;
label.text = $"Cost : {cost}";
titleContainer.Add(label);
}
}
Expand Down
14 changes: 7 additions & 7 deletions Editor/Node/GOAPGoalNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ namespace Kurisu.GOAP.Editor
{
public class GOAPGoalNode : GOAPNode
{
public GOAPGoalNode():base()
public GOAPGoalNode() : base()
{
label.style.color=Color.black;
label.style.color = Color.black;
}
private readonly Label label=new Label();
private readonly Label label = new Label();

protected sealed override void OnCleanUp()
{
titleContainer.Remove(label);
}
public void SetUp(float priority,bool canRun,bool isCurrent)
public void SetUp(float priority, bool canRun, bool isCurrent)
{
if(canRun)style.backgroundColor=isCurrent?Color.green:Color.yellow;
label.text=$"Priority : {priority}";
if (canRun) style.backgroundColor = isCurrent ? Color.green : Color.yellow;
label.text = $"Priority : {priority}";
titleContainer.Add(label);
}
}
Expand Down
42 changes: 20 additions & 22 deletions Editor/Node/GOAPNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@
using UnityEngine.UIElements;
namespace Kurisu.GOAP.Editor
{
public abstract class GOAPNode : UnityEditor.Experimental.GraphView.Node
public abstract class GOAPNode : Node
{
private GOAPView bindView;
public GOAPBehavior NodeBehavior {private set;get; }
public string GUID{get;protected set;}
private Type dirtyNodeBehaviorType;
public GOAPBehavior NodeBehavior { private set; get; }
public string GUID { get; protected set; }
private Type dirtyNodeBehaviorType;
private readonly VisualElement container;
private readonly TextField description;
public string Description=>description.value;
public string Description => description.value;
private readonly FieldResolverFactory fieldResolverFactory;
public readonly List<IFieldResolver> resolvers = new List<IFieldResolver>();
public Action<GOAPNode> onSelectAction;
Expand All @@ -24,13 +23,13 @@ public sealed override void OnSelected()
base.OnSelected();
onSelectAction?.Invoke(this);
}

protected GOAPNode()
{
fieldResolverFactory = FieldResolverFactory.Instance;
container = new VisualElement();
description = new TextField();
GUID=Guid.NewGuid().ToString();
GUID = Guid.NewGuid().ToString();
Initialize();
}

Expand All @@ -51,7 +50,7 @@ public void Restore(GOAPBehavior action)
NodeBehavior = action;
resolvers.ForEach(e => e.Restore(NodeBehavior));
description.value = NodeBehavior.description;
GUID=string.IsNullOrEmpty(action.GUID)?Guid.NewGuid().ToString():action.GUID;
GUID = string.IsNullOrEmpty(action.GUID) ? Guid.NewGuid().ToString() : action.GUID;
}
private GOAPBehavior ReplaceBehavior()
{
Expand All @@ -62,17 +61,16 @@ public Type GetBehavior()
{
return dirtyNodeBehaviorType;
}

public void Commit()
{
ReplaceBehavior();
resolvers.ForEach( r => r.Commit(NodeBehavior));
NodeBehavior.description = this.description.value;
NodeBehavior.GUID=this.GUID;
resolvers.ForEach(r => r.Commit(NodeBehavior));
NodeBehavior.description = description.value;
NodeBehavior.GUID = GUID;
}
public void SetBehavior(System.Type nodeBehavior,GOAPView view)
public void SetBehavior(Type nodeBehavior, GOAPView view)
{
this.bindView=view;
if (dirtyNodeBehaviorType != null)
{
dirtyNodeBehaviorType = null;
Expand All @@ -94,13 +92,13 @@ public void SetBehavior(System.Type nodeBehavior,GOAPView view)
container.Add(fieldResolver.GetEditorField());
resolvers.Add(fieldResolver);
});
var label=nodeBehavior.GetCustomAttribute(typeof(GOAPLabelAttribute), false) as GOAPLabelAttribute;
title = label?.Title??nodeBehavior.Name;
if(view.Set is IPlanner)
var label = nodeBehavior.GetCustomAttribute(typeof(GOAPLabelAttribute), false) as GOAPLabelAttribute;
title = label?.Title ?? nodeBehavior.Name;
if (view.Set is IPlanner)
{
capabilities&=~Capabilities.Copiable;
capabilities &=~Capabilities.Deletable;
capabilities &=~Capabilities.Movable;
capabilities &= ~Capabilities.Copiable;
capabilities &= ~Capabilities.Deletable;
capabilities &= ~Capabilities.Movable;
}
}

Expand All @@ -117,7 +115,7 @@ public void CleanUp()
{
style.backgroundColor = new StyleColor(StyleKeyword.Null);
}
protected virtual void OnCleanUp(){}
protected virtual void OnCleanUp() { }

}
}
10 changes: 5 additions & 5 deletions Editor/Node/NodeResovler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ namespace Kurisu.GOAP.Editor
{
public class NodeResolver
{
private const string NodeStyleSheetPath="AkiGOAP/Node";
private const string NodeStyleSheetPath = "AkiGOAP/Node";
private StyleSheet styleSheetCache;
public GOAPNode CreateNodeInstance(Type type,GOAPView view)
public GOAPNode CreateNodeInstance(Type type, GOAPView view)
{
GOAPNode node;
if (type.IsSubclassOf(typeof(GOAPGoal)))
Expand All @@ -17,9 +17,9 @@ public GOAPNode CreateNodeInstance(Type type,GOAPView view)
else
{
node = new GOAPActionNode();
}
node.SetBehavior(type,view);
if(styleSheetCache==null)styleSheetCache=Resources.Load<StyleSheet>(NodeStyleSheetPath);
}
node.SetBehavior(type, view);
if (styleSheetCache == null) styleSheetCache = Resources.Load<StyleSheet>(NodeStyleSheetPath);
node.styleSheets.Add(styleSheetCache);
return node;
}
Expand Down
21 changes: 18 additions & 3 deletions Editor/Window/GOAPEditorWindow.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
Expand Down Expand Up @@ -44,13 +45,27 @@ private VisualElement CreateToolBar(GOAPView graphView)
GUI.enabled = !Application.isPlaying;
if (GUILayout.Button($"Save", EditorStyles.toolbarButton))
{
var guiContent = new GUIContent();
graphView.Save();
guiContent.text = $"Update Succeed !";
ShowNotification(guiContent);
ShowNotification(new GUIContent("Update Succeed !"));
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
if (GUILayout.Button($"Save To Json", EditorStyles.toolbarButton))
{
string path = EditorUtility.SaveFilePanel("Select json file save path", Application.dataPath, graphView.Set.Object.name, "json");
if (!string.IsNullOrEmpty(path))
{
var template = CreateInstance<GOAPSet>();
template.Behaviors.AddRange(graphView.Set.Behaviors);
var serializedData = JsonUtility.ToJson(template);
FileInfo info = new(path);
File.WriteAllText(path, serializedData);
ShowNotification(new GUIContent("Save to json file succeed !"));
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
GUIUtility.ExitGUI();
}
GUILayout.EndHorizontal();
}
);
Expand Down
11 changes: 4 additions & 7 deletions Editor/Window/GOAPView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,11 @@ public GOAPView(EditorWindow editor, IGOAPSet set)
styleSheets.Add(Resources.Load<StyleSheet>(GraphStyleSheetPath));
SetupZoom(ContentZoomer.DefaultMinScale, ContentZoomer.DefaultMaxScale);
Insert(0, new GridBackground());

var contentDragger = new ContentDragger();
//鼠标中键移动
contentDragger.activators.Add(new ManipulatorActivationFilter()
{
button = MouseButton.MiddleMouse,
});
// 添加选框
this.AddManipulator(new SelectionDragger());
this.AddManipulator(new RectangleSelector());
this.AddManipulator(new FreehandSelector());
Expand Down Expand Up @@ -73,11 +70,11 @@ public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
base.BuildContextualMenu(evt);
var remainTargets = evt.menu.MenuItems().FindAll(e =>
{
switch (e)
return e switch
{
case DropdownMenuAction a: return a.name == "Create Node" || a.name == "Delete";
default: return false;
}
DropdownMenuAction a => a.name == "Create Node" || a.name == "Delete",
_ => false,
};
});
//Remove needless default actions .
evt.menu.MenuItems().Clear();
Expand Down
2 changes: 1 addition & 1 deletion Example/Scripts/Action/GoToHome.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public sealed override void OnTick()
{
agent.NavMeshAgent.SetDestination(agent.Home.position);
//You can make a trigger to set state or other method based on unity engine lifetime scope
worldState.SetState("CanRest", Vector3.SqrMagnitude(agent._Transform.position - agent.Home.position) < 1);
worldState.SetState("CanRest", Vector3.SqrMagnitude(agent.Transform.position - agent.Home.position) < 1);
}
}
}
2 changes: 1 addition & 1 deletion Example/Scripts/Action/GoToTent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public sealed override void OnTick()
{
agent.NavMeshAgent.SetDestination(agent.Tent.position);
//You can make a trigger to set state or other method based on unity engine lifetime scope
worldState.SetState("CanRest", Vector3.SqrMagnitude(agent._Transform.position - agent.Tent.position) < 1);
worldState.SetState("CanRest", Vector3.SqrMagnitude(agent.Transform.position - agent.Tent.position) < 1);
}
}
}
2 changes: 1 addition & 1 deletion Example/Scripts/Agent/AgentFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private void Awake()
var prefab = Instantiate(agentPrefab, GetRandomPosition(), Quaternion.identity);
agents[i] = new ExampleAgent(dataSet)
{
_Transform = prefab.transform,
Transform = prefab.transform,
Home = home,
Tent = tent,
Player = player
Expand Down
Loading

0 comments on commit c3c1886

Please sign in to comment.