File size: 9,434 Bytes
c69b4d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
170
171
172
173
174
175
176
177
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEditor.SceneManagement;
using UnityEngine;
using Unity.MLAgents.Policies;
using Unity.MLAgents.Actuators;

// Install in an isolated release-23 Project/Assets/Editor, then invoke
// -executeMethod VectorExtrasBuild.Build -simulationOutput <directory>.
public static class VectorExtrasBuild
{
    [Serializable] public class BehaviorInfo
    {
        public string name;
        public int team;
        public string stockPolicy;
        public string policyFile;
        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 = { "Match3VectorObs", "Basic", "3DBall", "PushBlockWithInput" };
            string[] allScenes = {
                "Match3/Scenes/Match3.unity", "Basic/Scenes/Basic.unity",
                "3DBall/Scenes/3DBall.unity", "PushBlockWithInput/Scenes/PushBlockWithInput.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);
                if (names[i] == "Match3VectorObs")
                {
                    var allBehaviors = scene.GetRootGameObjects()
                        .SelectMany(r => r.GetComponentsInChildren<BehaviorParameters>(true)).ToArray();
                    foreach (var b in allBehaviors)
                        if (b.BehaviorName != "Match3VectorObs")
                            UnityEngine.Object.DestroyImmediate(b.gameObject);
                }
                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(names[i]),
                    policyFile = names[i] + ".onnx",
                    continuous = CombinedSpec(b).NumContinuousActions,
                    branches = CombinedSpec(b).BranchSizes
                }).GroupBy(b => b.name + "?team=" + b.team).Select(g => g.First()).ToArray();
                if (behaviors.Length == 0) throw new Exception("No behaviors in " + names[i]);
                foreach (var component in scene.GetRootGameObjects()
                    .SelectMany(r => r.GetComponentsInChildren<MonoBehaviour>(true)))
                    if (component != null && component.GetType().Name == "CameraSensorComponent")
                        throw new Exception("Unexpected camera sensor: " + component.name);
                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, names[i] + ".onnx"), 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 ActionSpec CombinedSpec(BehaviorParameters behavior)
    {
        var components = behavior.GetComponentsInChildren<ActuatorComponent>(true);
        return ActionSpec.Combine(new[] { behavior.BrainParameters.ActionSpec }
            .Concat(components.Select(c => c.ActionSpec)).ToArray());
    }

    static string StockPolicyPath(string environment)
    {
        string folder = environment == "Match3VectorObs" ? "Match3" : environment;
        string filename = environment == "PushBlockWithInput" ? "PushBlock" : environment;
        string path = "Assets/ML-Agents/Examples/" + folder + "/TFModels/" + filename + ".onnx";
        if (!File.Exists(path)) throw new Exception("Missing external policy: " + path);
        return path;
    }
}