Download tools/VectorExtrasBuild.cs from ccnets/causal-gpt-rl-unity-envs: direct link, hf CLI and curl.
- Browser
- Download file 9.43 kB
-
https://huggingface.co/datasets/ccnets/causal-gpt-rl-unity-envs/resolve/main/tools/VectorExtrasBuild.cs
- Command line
-
hf download hf://datasets/ccnets/causal-gpt-rl-unity-envs/tools/VectorExtrasBuild.cs
-
curl -L -o VectorExtrasBuild.cs https://huggingface.co/datasets/ccnets/causal-gpt-rl-unity-envs/resolve/main/tools/VectorExtrasBuild.cs
9.43 kB
| 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 | |
| { | |
| [] public class BehaviorInfo | |
| { | |
| public string name; | |
| public int team; | |
| public string stockPolicy; | |
| public string policyFile; | |
| public int continuous; | |
| public int[] branches; | |
| } | |
| [] 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; | |
| } | |
| } | |