yum-slop/YOTS

an optimized toggle system for vrchat

git clone https://git.yummers.dev/yum-slop/YOTS

yumSkip YOTS if no config is on avatar4cb2a2b

v1.1.0
7.6 KiB194 linesraw
1#if UNITY_EDITOR
2
3using UnityEngine;
4using nadena.dev.ndmf;
5using nadena.dev.ndmf.builtin;
6using nadena.dev.ndmf.localization;
7using nadena.dev.ndmf.VRChat;
8using VRC.SDK3.Avatars.ScriptableObjects;
9using UnityEditor;
10using System;
11using System.Collections.Generic;
12using System.Linq;
13using UnityEditor.Animations;
14
15[assembly: ExportsPlugin(typeof(YOTS.YOTSNDMFGenerator))]
16
17namespace YOTS
18{
19  public class YOTSNDMFGenerator : Plugin<YOTSNDMFGenerator> {
20    private readonly Localizer localizer = new Localizer("en-us", () =>
21        new List<(string, Func<string, string>)> {
22        ("en-us", key => key)
23        });
24
25    public override string DisplayName => "YOTS Animator Generator";
26
27    protected override void Configure() {
28      // First pass: Retrieve and stash configuration
29      InPhase(BuildPhase.Resolving)
30        .Run("Cache YOTS Config", ctx => {
31          var config = ctx.AvatarRootObject.GetComponentInChildren<YOTSNDMFConfig>();
32          if (config == null) {
33            ctx.GetState<YOTSBuildState>().skipGeneration = true;
34            Debug.Log("No YOTS config found - skipping.");
35            return;
36          }
37          if (config.jsonConfig == null) {
38            ctx.GetState<YOTSBuildState>().skipGeneration = true;
39            ErrorReport.WithContextObject(ctx.AvatarRootObject, () => {
40                ErrorReport.ReportException(
41                    new Exception("No YOTS config found"), 
42                    "Missing required YOTS configuration"
43                );
44            });
45            return;
46          }
47          ctx.GetState<YOTSBuildState>().jsonConfig = config.jsonConfig.text;
48        })
49        // Shoutsout anatawa12/AvatarOptimizer
50        .BeforePass(RemoveEditorOnlyPass.Instance);
51
52      // Second pass: Generate and merge animator
53      InPhase(BuildPhase.Transforming)
54        .Run("Generate YOTS Animator", ctx => {
55          var config = ctx.GetState<YOTSBuildState>();
56          if (config.skipGeneration) {
57            return;
58          }
59          if (config == null) {
60            ErrorReport.WithContextObject(ctx.AvatarRootObject, () => {
61                ErrorReport.ReportException(
62                    new Exception("No YOTS config component found"), 
63                    "Missing required YOTS configuration"
64                );
65            });
66            return;
67          }
68          if (config.jsonConfig == null) {
69            ErrorReport.WithContextObject(ctx.AvatarRootObject, () => {
70                ErrorReport.ReportException(
71                    new Exception("Missing JSON config file"), 
72                    "YOTS config component is missing required JSON configuration"
73                );
74            });
75            return;
76          }
77
78          // Get menu and parameters
79          var descriptor = ctx.AvatarDescriptor;
80          if (descriptor == null) {
81            ErrorReport.WithContextObject(ctx.AvatarRootObject, () => {
82                ErrorReport.ReportException(
83                    new Exception("Avatar descriptor is missing"), 
84                    "Cannot find VRC Avatar Descriptor"
85                );
86            });
87            return;
88          }
89          RuntimeAnimatorController originalAnimator = descriptor.baseAnimationLayers[4].animatorController;
90          var menu = descriptor.expressionsMenu;
91          var parameters = descriptor.expressionParameters;
92          if (parameters == null || menu == null) {
93            ErrorReport.WithContextObject(descriptor, () => {
94                ErrorReport.ReportException(
95                    new Exception("Missing required VRC assets"), 
96                    "Avatar is missing required Expression Parameters or Menu"
97                );
98            });
99            return;
100          }
101          // Create copies so the originals don't get modified
102          menu = DeepCopyMenu(menu);
103          parameters = UnityEngine.Object.Instantiate(parameters);
104          descriptor.expressionsMenu = menu;
105          descriptor.expressionParameters = parameters;
106
107          // Generate the YOTS animator.
108          RuntimeAnimatorController generatedAnimator = YOTSCore.GenerateAnimator(
109              config.jsonConfig,
110              parameters,
111              menu
112          );
113          if (generatedAnimator == null) {
114            ErrorReport.WithContextObject(ctx.AvatarRootObject, () => {
115                ErrorReport.ReportException(
116                    new Exception("Failed to generate animator"), 
117                    "YOTS animator generation failed"
118                );
119            });
120            return;
121          }
122
123          // If no original animator, just assign the generated one.
124          if (originalAnimator == null) {
125            descriptor.baseAnimationLayers[4].animatorController = generatedAnimator;
126            return;
127          }
128          // Else append the generated animator to the original.
129          AnimatorController originalController = originalAnimator as AnimatorController;
130          AnimatorController generatedController = generatedAnimator as AnimatorController;
131          MergeAnimatorControllers(localizer, originalController, generatedController);
132          descriptor.baseAnimationLayers[4].animatorController = originalController;
133        });
134    }
135
136    // Simply append generated params and layers to the original animator.
137    private static void MergeAnimatorControllers(Localizer localizer, AnimatorController original, AnimatorController generated) {
138      // Merge parameters from generated into original.
139      foreach (var genParam in generated.parameters) {
140        // This is an O(m*n) check but m and n should be small enough to not matter.
141        if (original.parameters.Any(p => p.name == genParam.name)) {
142          ErrorReport.WithContextObject(original, () => {
143              ErrorReport.ReportException(
144                  new Exception($"Parameter '{genParam.name}' already exists"), 
145                  "Parameter name conflict in animator"
146              );
147          });
148          return;
149        }
150        original.AddParameter(genParam);
151      }
152
153      // Append each YOTS layer after the original layers.
154      foreach (var genLayer in generated.layers) {
155        // This isn't strictly an error but if someone already has layers named
156        // YOTS_* that's probably not on purpose.
157        if (original.layers.Any(l => l.name == genLayer.name)) {
158          ErrorReport.WithContextObject(original, () => {
159              ErrorReport.ReportException(
160                  new Exception($"Layer '{genLayer.name}' already exists"), 
161                  "Layer name conflict in animator"
162              );
163          });
164          return;
165        }
166        var newLayer = new AnimatorControllerLayer {
167          name = genLayer.name,
168          defaultWeight = genLayer.defaultWeight,
169          stateMachine = genLayer.stateMachine
170        };
171        original.AddLayer(newLayer);
172      }
173    }
174
175    private class YOTSBuildState {
176      public string jsonConfig;
177      public bool skipGeneration;
178    }
179
180    private static VRCExpressionsMenu DeepCopyMenu(VRCExpressionsMenu sourceMenu) {
181        var copiedMenu = UnityEngine.Object.Instantiate(sourceMenu);
182        // Deep copy all submenu references
183        for (int i = 0; i < copiedMenu.controls.Count; i++) {
184            var control = copiedMenu.controls[i];
185            if (control.type == VRCExpressionsMenu.Control.ControlType.SubMenu) {
186                control.subMenu = DeepCopyMenu(control.subMenu);
187            }
188        }
189        return copiedMenu;
190    }
191  }
192}
193
194#endif  // UNITY_EDITOR