causal-gpt-rl-unity-envs / tools /AdditionalSimulationBuild.cs
kissin42's picture
Add model-removed Hallway, GridWorld, Sorter and WallJump simulations
546d427 verified
Raw History Blame Contribute Delete
8.91 kB
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);
}
}