File size: 8,906 Bytes
36743eb 546d427 36743eb 546d427 36743eb 546d427 36743eb 546d427 36743eb 546d427 36743eb 546d427 36743eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEditor.SceneManagement;
using UnityEngine;
using Unity.MLAgents.Policies;
// Install in an isolated release-23 Project/Assets/Editor, then invoke
// -executeMethod AdditionalSimulationBuild.Build -simulationOutput <directory>.
public static class AdditionalSimulationBuild
{
[Serializable] public class BehaviorInfo
{
public string name;
public int team;
public string stockPolicy;
public int continuous;
public int[] branches;
}
[Serializable] public class Manifest
{
public string environment;
public string sourceScene;
public string unityVersion;
public string platform;
public bool modelRemoved;
public BehaviorInfo[] behaviors;
public string[] packedPolicies;
}
public static void Build()
{
try
{
var args = Environment.GetCommandLineArgs();
int idx = Array.IndexOf(args, "-simulationOutput");
if (idx < 0 || idx + 1 >= args.Length)
throw new ArgumentException("-simulationOutput is required");
string output = Path.GetFullPath(args[idx + 1]);
int targetIndex = Array.IndexOf(args, "-simulationTarget");
var target = targetIndex < 0 ? BuildTarget.StandaloneWindows64 :
(BuildTarget)Enum.Parse(typeof(BuildTarget), args[targetIndex + 1]);
if (target != BuildTarget.StandaloneWindows64 && target != BuildTarget.StandaloneLinux64)
throw new ArgumentException("Only Windows64 and Linux64 are supported");
string[] allNames = { "PushBlockCollab", "FoodCollector", "StrikersVsGoalie",
"Hallway", "GridWorld", "Sorter", "WallJump" };
string[] allScenes = {
"PushBlock/Scenes/PushBlockCollab.unity",
"FoodCollector/Scenes/FoodCollector.unity",
"Soccer/Scenes/StrikersVsGoalie.unity",
"Hallway/Scenes/Hallway.unity", "GridWorld/Scenes/GridWorld.unity",
"Sorter/Scenes/Sorter.unity", "WallJump/Scenes/WallJump.unity"
};
int selectionIndex = Array.IndexOf(args, "-simulationEnvironments");
string[] names = selectionIndex < 0 ? allNames : args[selectionIndex + 1].Split(',');
foreach (var name in names)
if (!allNames.Contains(name)) throw new ArgumentException("Unknown scene: " + name);
Directory.CreateDirectory("Assets/SimulationBuildScenes");
AssetDatabase.Refresh();
for (int i = 0; i < names.Length; i++)
{
string source = "Assets/ML-Agents/Examples/" + allScenes[Array.IndexOf(allNames, names[i])];
var scene = EditorSceneManager.OpenScene(source, OpenSceneMode.Single);
// Unpack copies so prefab model references cannot enter the build.
foreach (var root in scene.GetRootGameObjects())
if (PrefabUtility.IsPartOfPrefabInstance(root))
PrefabUtility.UnpackPrefabInstance(root, PrefabUnpackMode.Completely,
InteractionMode.AutomatedAction);
var behaviors = scene.GetRootGameObjects()
.SelectMany(r => r.GetComponentsInChildren<BehaviorParameters>(true)).ToArray();
var info = behaviors.Select(b => new BehaviorInfo {
name = b.BehaviorName, team = b.TeamId,
stockPolicy = StockPolicyPath(b),
continuous = b.BrainParameters.ActionSpec.NumContinuousActions,
branches = b.BrainParameters.ActionSpec.BranchSizes
}).GroupBy(b => b.name + "?team=" + b.team).Select(g => g.First()).ToArray();
if (names[i] == "WallJump")
info = new[] { "SmallWallJump", "BigWallJump" }.Select(name => new BehaviorInfo {
name = name, team = info[0].team,
stockPolicy = "Assets/ML-Agents/Examples/WallJump/TFModels/" + name + ".onnx",
continuous = info[0].continuous, branches = info[0].branches
}).ToArray();
foreach (var b in behaviors)
{
b.Model = null;
b.BehaviorType = BehaviorType.Default;
EditorUtility.SetDirty(b);
}
// Remove any other serialized ONNX/NN references on scene components.
foreach (var component in scene.GetRootGameObjects()
.SelectMany(r => r.GetComponentsInChildren<MonoBehaviour>(true)))
{
if (component == null) continue;
var serialized = new SerializedObject(component);
var property = serialized.GetIterator();
bool changed = false;
while (property.Next(true))
{
if (property.propertyType != SerializedPropertyType.ObjectReference) continue;
string path = AssetDatabase.GetAssetPath(property.objectReferenceValue);
if (path.EndsWith(".onnx", StringComparison.OrdinalIgnoreCase) ||
path.EndsWith(".nn", StringComparison.OrdinalIgnoreCase))
{
property.objectReferenceValue = null;
changed = true;
}
}
if (changed) serialized.ApplyModifiedPropertiesWithoutUndo();
}
string staged = "Assets/SimulationBuildScenes/" + names[i] + ".unity";
if (!EditorSceneManager.SaveScene(scene, staged))
throw new Exception("Could not save " + staged);
string envOutput = Path.Combine(output, names[i]);
Directory.CreateDirectory(envOutput);
foreach (var policy in info.Select(b => b.stockPolicy).Where(p => !string.IsNullOrEmpty(p)).Distinct())
{
string policies = Path.Combine(output, "policies", names[i]);
Directory.CreateDirectory(policies);
File.Copy(policy, Path.Combine(policies, Path.GetFileName(policy)), true);
}
var report = BuildPipeline.BuildPlayer(new BuildPlayerOptions {
scenes = new[] { staged },
locationPathName = Path.Combine(envOutput, names[i] +
(target == BuildTarget.StandaloneWindows64 ? ".exe" : ".x86_64")),
target = target,
options = BuildOptions.StrictMode
});
if (report.summary.result != BuildResult.Succeeded)
throw new Exception(names[i] + " build failed: " + report.summary.result);
var packed = report.packedAssets.SelectMany(p => p.contents)
.Select(a => a.sourceAssetPath).Where(p => p.EndsWith(".onnx") || p.EndsWith(".nn"))
.Distinct().ToArray();
var manifest = new Manifest {
environment = names[i], sourceScene = source,
unityVersion = Application.unityVersion, platform = target.ToString(),
modelRemoved = packed.Length == 0,
behaviors = info, packedPolicies = packed
};
File.WriteAllText(Path.Combine(envOutput, "simulation-build.json"), JsonUtility.ToJson(manifest, true));
if (packed.Length > 0)
throw new Exception("Baked policies found: " + string.Join(", ", packed));
Debug.Log("SIMULATION_BUILD_OK " + names[i] + " " + report.summary.totalSize);
}
EditorApplication.Exit(0);
}
catch (Exception error)
{
Debug.LogException(error);
EditorApplication.Exit(1);
}
}
static string StockPolicyPath(BehaviorParameters behavior)
{
string path = AssetDatabase.GetAssetPath(behavior.Model);
if (!string.IsNullOrEmpty(path)) return path;
// Some older scene prefabs still reference the obsolete Barracuda GUID.
if (behavior.BehaviorName == "PushBlockCollab")
return "Assets/ML-Agents/Examples/PushBlock/TFModels/PushBlockCollab.onnx";
if (behavior.BehaviorName == "Hallway" || behavior.BehaviorName == "GridWorld")
return "Assets/ML-Agents/Examples/" + behavior.BehaviorName + "/TFModels/" +
behavior.BehaviorName + ".onnx";
throw new Exception("No stock policy mapped for " + behavior.BehaviorName);
}
}
|