@babylonjs-toolkit/agent 1.2.9 → 1.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,55 @@ public static class BtOptimize
21
21
  /// <summary>Render queues from here up are transparent.</summary>
22
22
  private const int FirstTransparentQueue = 2500;
23
23
 
24
+ /// <summary>A rigid skinned mesh keeps its own mesh when its bind pose moves no vertex by more than this many units.</summary>
25
+ private const float RestPoseToleranceUnits = 0.01f;
26
+
27
+ /// <summary>The rest-pose tolerance as a share of the mesh's size, for meshes too large for the fixed tolerance.</summary>
28
+ private const float RestPoseRelativeTolerance = 0.0005f;
29
+
30
+ /// <summary>Skinning verdict: one bone that moves with the object — converts to MeshFilter + MeshRenderer.</summary>
31
+ private const string SkinRigid = "rigid — needs no skinning";
32
+
33
+ /// <summary>
34
+ /// Skinning verdict: rigid, but its bind pose places the mesh away from its object — converts to a plain mesh with
35
+ /// that fixed offset baked in, one mesh asset shared by every copy with the same offset (so they still instance).
36
+ /// </summary>
37
+ private const string SkinRigidOffset = "rigid — needs no skinning (offset baked)";
38
+
39
+ /// <summary>Offset matrices and baked pose vertices are compared at this precision when copies share one baked mesh.</summary>
40
+ private const int SharedMeshKeyDecimals = 4;
41
+
42
+ /// <summary>
43
+ /// Skinning verdict: one bone, and the only thing that seemed to move it apart from the object is a toolkit script
44
+ /// on the renderer's own object — converts to a plain mesh baked as it is drawn now (the script stays).
45
+ /// </summary>
46
+ private const string SkinRigidScriptHost = "rigid — a script sits on the object; Tune bakes it in place";
47
+
48
+ /// <summary>
49
+ /// Skinning verdict: rigid, but a clip animates the SkinnedMeshRenderer itself — converts like a rigid mesh, and the
50
+ /// clip is copied with those curves aimed at MeshRenderer, on a copy of the Animator's controller.
51
+ /// </summary>
52
+ private const string SkinRigidRendererCurves = "rigid — Tune retargets its renderer curves";
53
+
54
+ /// <summary>
55
+ /// Skinning verdict: rigid, but converting would change it — its bone moves apart from the object (a clip, Timeline,
56
+ /// constraint or physics body), a component references the SkinnedMeshRenderer, or a clip Tune cannot retarget (a
57
+ /// legacy Animation, an override controller) animates it.
58
+ /// </summary>
59
+ private const string SkinRigidByHand = "rigid — convert by hand";
60
+
61
+ /// <summary>
62
+ /// Skinning verdict: several weighted bones that nothing moves apart from the object — the pose never changes. Tune
63
+ /// bakes the pose to a static mesh, copies with the same pose sharing one mesh asset.
64
+ /// </summary>
65
+ private const string SkinFrozenPose = "frozen pose — bake to a static mesh";
66
+
67
+ /// <summary>Skinning verdict: really deforms (animated bones, blend shapes or cloth).</summary>
68
+ private const string SkinDeforms = "deforms — really skinned";
69
+
70
+ /// <summary>Why --keep-gi leaves an object out of the bake (see TuneOptions.keepSourceGI).</summary>
71
+ private const string KeepGIReason = "keep-gi: not a GI contributor in the source";
72
+
24
73
  // ------------------------------------------------------------------------------------------------------------
25
74
  // Survey
26
75
  // ------------------------------------------------------------------------------------------------------------
@@ -43,6 +92,8 @@ public static class BtOptimize
43
92
 
44
93
  SurveyLights(context, md, json);
45
94
  SurveyRenderers(context, md, json);
95
+ SurveySkinning(context, md, json);
96
+ SurveyRepeats(context, md, json);
46
97
  SurveyPostProcessing(context, md, json);
47
98
  SurveyPipeline(md, json);
48
99
  SurveyExporter(context, md, json);
@@ -147,6 +198,108 @@ public static class BtOptimize
147
198
  { "mirroredGroups", GroupsToJson(mirroredGroups) } };
148
199
  }
149
200
 
201
+ /// <summary>
202
+ /// Every skinned renderer and whether it really needs skinning. A skinned mesh in BabylonJS is skinned every frame,
203
+ /// and copies of one that animate separately can never share an instanced draw: each copy is its own draw in every
204
+ /// pass. DAE / FBX imports often make rigid props (coins, item boxes, trees, signs) one-bone skinned meshes that
205
+ /// bought nothing — those convert to MeshFilter + MeshRenderer (Tune `unskinRigid`).
206
+ /// </summary>
207
+ private static void SurveySkinning(Context context, StringBuilder md, Dictionary<string, object> json)
208
+ {
209
+ var rows = new List<object>();
210
+ var verdictCounts = new Dictionary<string, int>();
211
+ md.AppendLine("## Skinned meshes — which ones need skinning");
212
+ md.AppendLine();
213
+ var skinnedRenderers = context.Renderers.OfType<SkinnedMeshRenderer>().ToList();
214
+ if (skinnedRenderers.Count == 0) { md.AppendLine("None."); md.AppendLine(); json["skinning"] = rows; return; }
215
+ md.AppendLine("| Mesh | Copies | Verdict | Why | Next step | Example |");
216
+ md.AppendLine("|---|---|---|---|---|---|");
217
+ var groups = skinnedRenderers.Select(renderer => new { renderer, verdict = ClassifySkinning(renderer, context) })
218
+ .GroupBy(entry => (entry.renderer.sharedMesh != null ? entry.renderer.sharedMesh.name : "none") + "|" + entry.verdict.Kind)
219
+ .OrderByDescending(group => group.Count());
220
+ foreach (var group in groups)
221
+ {
222
+ var first = group.First();
223
+ int copies = group.Count();
224
+ string nextStep = NextStepForSkinning(first.verdict.Kind, copies);
225
+ verdictCounts[first.verdict.Kind] = verdictCounts.TryGetValue(first.verdict.Kind, out var count) ? count + copies : copies;
226
+ string meshName = first.renderer.sharedMesh != null ? first.renderer.sharedMesh.name : "none";
227
+ md.AppendLine("| " + meshName + " | " + copies + " | " + first.verdict.Kind + " | " + first.verdict.Why + " | " + nextStep + " | " + PathOf(first.renderer.transform) + " |");
228
+ rows.Add(new Dictionary<string, object> { { "mesh", meshName }, { "copies", copies }, { "verdict", first.verdict.Kind }, { "why", first.verdict.Why },
229
+ { "nextStep", nextStep }, { "example", PathOf(first.renderer.transform) } });
230
+ }
231
+ md.AppendLine();
232
+ md.AppendLine("Skinned renderers: **" + skinnedRenderers.Count + "** — " + string.Join(", ", verdictCounts.Select(pair => pair.Key + " " + pair.Value)) + ".");
233
+ md.AppendLine();
234
+ context.Summary.AppendLine("skinned=" + skinnedRenderers.Count + " " + string.Join(" ", verdictCounts.Select(pair => "[" + pair.Key + "]=" + pair.Value)));
235
+ json["skinning"] = rows;
236
+ }
237
+
238
+ /// <summary>What to do about a group of skinned renderers with the given verdict.</summary>
239
+ private static string NextStepForSkinning(string verdictKind, int copies)
240
+ {
241
+ if (verdictKind == SkinRigid) return "Tune converts it (unskinRigid)";
242
+ if (verdictKind == SkinRigidOffset) return "Tune converts it to a shared baked mesh (unskinRigid)";
243
+ if (verdictKind == SkinRigidScriptHost) return "Tune bakes it to a plain mesh in place (unskinRigid)";
244
+ if (verdictKind == SkinRigidRendererCurves) return "Tune converts it and retargets the clip to MeshRenderer (unskinRigid)";
245
+ if (verdictKind == SkinRigidByHand) return "convert by hand (see Why), then re-survey";
246
+ if (verdictKind == SkinFrozenPose) return "Tune bakes it to a static mesh";
247
+ return copies > 1 ? "repeated deforming mesh: candidate for the toolkit AnimatorControlRig VAT (crowd) mode — instanced, one draw" : "keep";
248
+ }
249
+
250
+ /// <summary>
251
+ /// Every mesh drawn more than once with the same materials, and whether its copies can share one instanced draw in
252
+ /// BabylonJS. The exporter writes repeated meshes as glTF instances (ExportMeshInstances), but never skinned or
253
+ /// lightmapped copies, and a material splits into copies per reflection probe. Repeated props are usually the
254
+ /// largest group of draws in a level after the level geometry itself.
255
+ /// </summary>
256
+ private static void SurveyRepeats(Context context, StringBuilder md, Dictionary<string, object> json)
257
+ {
258
+ var rows = new List<object>();
259
+ md.AppendLine("## Repeated meshes — do the copies share one draw?");
260
+ md.AppendLine();
261
+ md.AppendLine("| Mesh | Copies | Draws now (est.) | Draws if instanced | What stops sharing | Example |");
262
+ md.AppendLine("|---|---|---|---|---|---|");
263
+ int drawsNow = 0, drawsInstanced = 0;
264
+ var repeated = context.Renderers.GroupBy(RepeatKey).Where(group => group.Count() > 1).OrderByDescending(group => group.Count() * SubMeshCount(group.First()));
265
+ foreach (var group in repeated)
266
+ {
267
+ var renderers = group.ToList();
268
+ int subMeshes = SubMeshCount(renderers[0]);
269
+ var blockers = InstancingBlockers(renderers, context);
270
+ int probeZones = renderers.Select(DominantReflectionProbe).Distinct().Count();
271
+ int groupDrawsNow = blockers.Count == 0 ? subMeshes * probeZones : subMeshes * renderers.Count;
272
+ drawsNow += groupDrawsNow;
273
+ drawsInstanced += subMeshes * probeZones;
274
+ string meshName = MeshOf(renderers[0]) != null ? MeshOf(renderers[0]).name : renderers[0].name;
275
+ string blockerText = blockers.Count == 0 ? (probeZones > 1 ? "shares (one draw per reflection probe zone: " + probeZones + ")" : "shares one draw") : string.Join("; ", blockers);
276
+ md.AppendLine("| " + meshName + " | " + renderers.Count + " | " + groupDrawsNow + " | " + subMeshes * probeZones + " | " + blockerText + " | " + PathOf(renderers[0].transform) + " |");
277
+ rows.Add(new Dictionary<string, object> { { "mesh", meshName }, { "copies", renderers.Count }, { "drawsNow", groupDrawsNow }, { "drawsIfInstanced", subMeshes * probeZones },
278
+ { "blockers", blockers.Cast<object>().ToList() }, { "example", PathOf(renderers[0].transform) } });
279
+ }
280
+ md.AppendLine();
281
+ md.AppendLine("Repeated-mesh draws (one pass, all copies in view): **" + drawsNow + "** now, **" + drawsInstanced + "** if every group shared its draw.");
282
+ md.AppendLine();
283
+ context.Summary.AppendLine("repeatedDraws now=" + drawsNow + " instanced=" + drawsInstanced);
284
+ json["repeats"] = new Dictionary<string, object> { { "drawsNow", drawsNow }, { "drawsIfInstanced", drawsInstanced }, { "groups", rows } };
285
+ }
286
+
287
+ /// <summary>Why copies of one mesh cannot share an instanced draw in BabylonJS (empty when they can).</summary>
288
+ private static List<string> InstancingBlockers(List<Renderer> renderers, Context context)
289
+ {
290
+ var blockers = new List<string>();
291
+ var skinned = renderers.OfType<SkinnedMeshRenderer>().ToList();
292
+ if (skinned.Count > 0)
293
+ {
294
+ string verdict = ClassifySkinning(skinned[0], context).Kind;
295
+ blockers.Add("skinned ×" + skinned.Count + " (" + verdict + ")");
296
+ }
297
+ int lightmapped = renderers.OfType<MeshRenderer>().Count(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
298
+ && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
299
+ if (lightmapped > 0) blockers.Add("lightmapped ×" + lightmapped + " (each lightmapped copy is exported as its own mesh)");
300
+ return blockers;
301
+ }
302
+
150
303
  /// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
151
304
  private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
152
305
  {
@@ -299,6 +452,24 @@ public static class BtOptimize
299
452
  public string[] keepLights = new string[0];
300
453
  /// <summary>Turn realtime shadows off on point / spot lights that stay runtime (each is a full scene pass per frame, six for a point light).</summary>
301
454
  public bool pointSpotShadowsOff = true;
455
+ /// <summary>
456
+ /// Replace SkinnedMeshRenderers that need no skinning (one weighted bone moving with the object, no blend shapes
457
+ /// or cloth, rest pose equal to the mesh) with MeshFilter + MeshRenderer on the same mesh and materials. Animators
458
+ /// stay: transform, child and collider curves keep working. Runs first, so the other steps see the new renderers.
459
+ /// </summary>
460
+ public bool unskinRigid = true;
461
+ /// <summary>
462
+ /// A mesh drawn this many times or more (same mesh and materials) is not lightmapped (lightmapped copies never
463
+ /// share), and its copies get Light Probe Usage Off so they share one instanced draw: the toolkit loads every
464
+ /// probe-lit node as its own mesh (SceneManager.DeinstanceProbeLitNodes). 0 turns the rule off.
465
+ /// </summary>
466
+ public int instanceRepeatsFrom = 4;
467
+ /// <summary>
468
+ /// Keep Contribute GI exactly as the source scene has it (the source named in working-copy.txt): no step adds
469
+ /// Contribute GI to an object that did not contribute in the source, so the re-bake keeps the source's indirect
470
+ /// light. Off by default, because merging needs the newly lightmapped props.
471
+ /// </summary>
472
+ public bool keepSourceGI = false;
302
473
  /// <summary>Mark renderers static when nothing in the browser can move them.</summary>
303
474
  public bool markStatic = true;
304
475
  /// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
@@ -328,14 +499,26 @@ public static class BtOptimize
328
499
  string folder = ReportFolder(scene);
329
500
  if (!options.dryRun && !File.Exists(Path.Combine(folder, "working-copy.txt")))
330
501
  throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; Tune never edits a source scene.");
331
- var context = new Context(scene);
502
+ var sourceGIContributors = SourceGIContributorsOf(scene, folder);
503
+ var context = new Context(scene, sourceGIContributors);
332
504
  var changes = new List<Change>();
333
505
  var kept = new List<Change>();
334
506
 
507
+ if (options.unskinRigid)
508
+ {
509
+ int converted = UnskinRigid(context, options, changes, kept);
510
+ // The converted objects now have MeshRenderers: gather the scene again so the static and lightmap steps see them.
511
+ if (converted > 0 && !options.dryRun) context = new Context(scene, sourceGIContributors);
512
+ }
335
513
  if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
336
514
  if (options.markStatic) MarkStatic(context, options, changes, kept);
337
515
  if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
516
+ if (options.instanceRepeatsFrom > 0) InstanceRepeats(context, options, changes, kept);
338
517
  if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
518
+ // A dry run changed no flags, so its copy count is the one the planned changes would leave.
519
+ int copyGIContributors = options.dryRun ? context.PlannedGIContributors.Count : GIContributorPaths(scene.GetRootGameObjects()).Count;
520
+ string giContributorsLine = "GI contributors: source " + sourceGIContributors.Count + " → copy " + copyGIContributors
521
+ + (options.keepSourceGI ? " (--keep-gi)" : "");
339
522
 
340
523
  if (!options.dryRun)
341
524
  {
@@ -345,6 +528,7 @@ public static class BtOptimize
345
528
  }
346
529
 
347
530
  var md = new StringBuilder("# bt-optimize tune" + (options.dryRun ? " plan (dry run — nothing changed)" : "") + " — " + scene.path + "\n\n");
531
+ md.AppendLine(giContributorsLine + "\n");
348
532
  foreach (var kind in changes.Select(change => change.Kind).Distinct())
349
533
  {
350
534
  var list = changes.Where(change => change.Kind == kind).ToList();
@@ -360,16 +544,184 @@ public static class BtOptimize
360
544
  File.WriteAllText(Path.Combine(folder, stem + ".md"), md.ToString());
361
545
  File.WriteAllText(Path.Combine(folder, stem + ".json"), ToJson(new Dictionary<string, object> {
362
546
  { "scene", scene.path },
547
+ { "giContributors", new Dictionary<string, object> { { "source", sourceGIContributors.Count }, { "copy", copyGIContributors }, { "keepSourceGI", options.keepSourceGI } } },
363
548
  { "changes", changes.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "before", change.Before }, { "after", change.After }, { "why", change.Why } }).ToList() },
364
549
  { "kept", kept.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "why", change.Why } }).ToList() } }, 0));
365
550
 
366
551
  var summary = new StringBuilder("tuned=" + scene.path + "\n");
367
552
  foreach (var group in changes.GroupBy(change => change.Kind)) summary.AppendLine(" " + group.Key + ": " + group.Count());
368
553
  foreach (var group in kept.GroupBy(change => change.Kind)) summary.AppendLine(" kept " + group.Key + ": " + group.Count());
554
+ summary.AppendLine(giContributorsLine);
369
555
  summary.AppendLine("needsBake=" + changes.Any(change => change.Kind != "Volume profile"));
370
556
  return summary.ToString();
371
557
  }
372
558
 
559
+ /// <summary>
560
+ /// Replaces every skinned renderer that needs no skinning with a MeshFilter + MeshRenderer. An Animator on the object
561
+ /// is not a reason to skip it: Animators that move, scale or toggle the object (spawn pops, spins, bobs) keep working
562
+ /// on a plain mesh. One-bone props keep their mesh (or a shared offset-baked copy); a script host and a frozen pose
563
+ /// are baked as they are drawn now, copies with the same shape sharing one mesh asset; a clip that animates the
564
+ /// SkinnedMeshRenderer itself is copied with its curves aimed at MeshRenderer, on a copy of its controller. Only real
565
+ /// deformation and the still-manual cases (see SkinRigidByHand) keep a renderer skinned.
566
+ /// </summary>
567
+ /// <returns>How many renderers were converted (or would be, in a dry run).</returns>
568
+ private static int UnskinRigid(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
569
+ {
570
+ int converted = 0;
571
+ var bakedMeshes = new Dictionary<string, Mesh>();
572
+ string bakedFolder = UnskinnedMeshFolder(context.Scene);
573
+ string clipFolder = RetargetedClipFolder(context.Scene);
574
+ var curveAnimators = new List<Animator>();
575
+ foreach (var renderer in context.Renderers.OfType<SkinnedMeshRenderer>().ToList())
576
+ {
577
+ string path = PathOf(renderer.transform);
578
+ if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "skinned", Path = path, Why = "--exclude" }); continue; }
579
+ var verdict = ClassifySkinning(renderer, context);
580
+ int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
581
+ string copiesNote = copies > 1 ? " — " + copies + " copies" : "";
582
+ if (!TuneConverts(verdict.Kind))
583
+ {
584
+ kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
585
+ continue;
586
+ }
587
+ bool bakesPose = verdict.Kind == SkinRigidScriptHost || verdict.Kind == SkinFrozenPose;
588
+ string howPlaced;
589
+ var mesh = bakesPose
590
+ ? BakedPoseMesh(renderer, bakedFolder, bakedMeshes, !options.dryRun, out howPlaced)
591
+ : PlacedRigidMesh(renderer, verdict, context, options.dryRun, bakedFolder, bakedMeshes, out howPlaced);
592
+ var animators = AnimatorsWithRendererCurves(renderer);
593
+ curveAnimators.AddRange(animators);
594
+ string retargetNote = animators.Count > 0 ? "; " + RetargetPlan(animators, renderer.transform, clipFolder) : "";
595
+ bool clearsContributeGI = WithheldContributeGI(renderer.gameObject, path, context, options);
596
+ changes.Add(new Change { Kind = UnskinnedChangeKind(verdict.Kind), Path = path, Before = "SkinnedMeshRenderer, " + verdict.Why,
597
+ After = "MeshFilter + MeshRenderer, " + howPlaced + ", same materials",
598
+ Why = UnskinnedReason(verdict.Kind) + copiesNote + retargetNote + (clearsContributeGI ? "; Contribute GI cleared — " + KeepGIReason : "") });
599
+ converted++;
600
+ if (options.dryRun)
601
+ {
602
+ context.PlannedUnskinned.Add(renderer);
603
+ continue;
604
+ }
605
+ var gameObject = renderer.gameObject;
606
+ ReplaceWithMeshRenderer(renderer, mesh);
607
+ if (clearsContributeGI) GameObjectUtility.SetStaticEditorFlags(gameObject, GameObjectUtility.GetStaticEditorFlags(gameObject) & ~StaticEditorFlags.ContributeGI);
608
+ }
609
+ if (options.dryRun)
610
+ {
611
+ DiscardUnsavedMeshes(bakedMeshes.Values);
612
+ return converted;
613
+ }
614
+ RetargetAnimators(curveAnimators.Distinct().ToList(), clipFolder);
615
+ if (bakedMeshes.Count > 0 || curveAnimators.Count > 0) AssetDatabase.SaveAssets();
616
+ return converted;
617
+ }
618
+
619
+ /// <summary>True for the skinning verdicts UnskinRigid converts to a plain mesh.</summary>
620
+ private static bool TuneConverts(string verdictKind)
621
+ {
622
+ return verdictKind == SkinRigid || verdictKind == SkinRigidOffset || verdictKind == SkinRigidScriptHost
623
+ || verdictKind == SkinRigidRendererCurves || verdictKind == SkinFrozenPose;
624
+ }
625
+
626
+ /// <summary>The tune.md change kind for a converted verdict.</summary>
627
+ private static string UnskinnedChangeKind(string verdictKind)
628
+ {
629
+ if (verdictKind == SkinRigidScriptHost) return "Unskinned (script host)";
630
+ if (verdictKind == SkinRigidRendererCurves) return "Unskinned (renderer curves)";
631
+ if (verdictKind == SkinFrozenPose) return "Unskinned (frozen pose)";
632
+ return "Unskinned (rigid)";
633
+ }
634
+
635
+ /// <summary>Why converting a renderer with this verdict is safe and what it buys.</summary>
636
+ private static string UnskinnedReason(string verdictKind)
637
+ {
638
+ const string buys = "BabylonJS skins it every frame, and skinned copies can never share an instanced draw";
639
+ if (verdictKind == SkinRigidScriptHost) return "the script on its own object stays and moves nothing apart from the mesh; baked as it is drawn now — " + buys;
640
+ if (verdictKind == SkinFrozenPose) return "its pose never changes; baked once, and copies with the same pose share the mesh asset — " + buys;
641
+ return "skinning bought nothing: " + buys;
642
+ }
643
+
644
+ /// <summary>
645
+ /// The mesh a one-bone renderer draws once converted. Its own mesh when the bind pose matches; otherwise the leaf
646
+ /// object is moved onto the bind pose (the mesh stays shared by every copy), and only when that is impossible is
647
+ /// the offset baked into a mesh asset. A dry run changes nothing and returns the skinned mesh.
648
+ /// </summary>
649
+ private static Mesh PlacedRigidMesh(SkinnedMeshRenderer renderer, SkinningVerdict verdict, Context context, bool dryRun, string bakedFolder,
650
+ Dictionary<string, Mesh> bakedMeshes, out string howPlaced)
651
+ {
652
+ var mesh = renderer.sharedMesh;
653
+ howPlaced = "same mesh";
654
+ if (!verdict.OffsetBaked) return mesh;
655
+ bool reseat = CanReseatObject(renderer, context);
656
+ if (!dryRun)
657
+ {
658
+ if (reseat) reseat = TryReseatObject(renderer.transform, mesh, verdict.MeshToWorld, RestPoseTolerance(renderer));
659
+ if (!reseat) mesh = BakeOffsetMesh(mesh, verdict.MeshToObject, bakedFolder, bakedMeshes);
660
+ }
661
+ howPlaced = reseat ? "same mesh, object moved onto the bind pose" : "baked mesh in " + bakedFolder;
662
+ return mesh;
663
+ }
664
+
665
+ /// <summary>
666
+ /// True when --keep-gi must clear Contribute GI on a converted object: it carries the flag (a SkinnedMeshRenderer
667
+ /// never takes part in the bake, the MeshRenderer that replaces it would) and did not contribute in the source.
668
+ /// Keeps the context's planned contributor set in step.
669
+ /// </summary>
670
+ private static bool WithheldContributeGI(GameObject gameObject, string path, Context context, TuneOptions options)
671
+ {
672
+ if (!GameObjectUtility.GetStaticEditorFlags(gameObject).HasFlag(StaticEditorFlags.ContributeGI)) return false;
673
+ if (WithheldFromBake(path, context, options)) return true;
674
+ context.PlannedGIContributors.Add(path);
675
+ return false;
676
+ }
677
+
678
+ /// <summary>Destroys the in-memory meshes a dry run baked to compare shapes (none of them was saved).</summary>
679
+ private static void DiscardUnsavedMeshes(IEnumerable<Mesh> meshes)
680
+ {
681
+ foreach (var mesh in meshes.Where(mesh => !EditorUtility.IsPersistent(mesh)).ToList()) UnityEngine.Object.DestroyImmediate(mesh);
682
+ }
683
+
684
+ /// <summary>
685
+ /// Swaps a SkinnedMeshRenderer for a MeshFilter + MeshRenderer on the same GameObject drawing `mesh` (the skinned
686
+ /// mesh itself, its offset-baked copy or its baked pose), with the same materials and renderer settings: shadow
687
+ /// casting and receiving, occlusion, both probe usages, the probe anchor, motion vectors, rendering layers and
688
+ /// sorting. Bones, colliders, Animators and static flags stay as they are.
689
+ /// </summary>
690
+ private static void ReplaceWithMeshRenderer(SkinnedMeshRenderer skinned, Mesh mesh)
691
+ {
692
+ var gameObject = skinned.gameObject;
693
+ var materials = skinned.sharedMaterials;
694
+ var shadowCasting = skinned.shadowCastingMode;
695
+ bool receiveShadows = skinned.receiveShadows, wasEnabled = skinned.enabled, allowOcclusion = skinned.allowOcclusionWhenDynamic;
696
+ var probeUsage = skinned.lightProbeUsage;
697
+ var reflectionUsage = skinned.reflectionProbeUsage;
698
+ var probeAnchor = skinned.probeAnchor;
699
+ var motionVectors = skinned.motionVectorGenerationMode;
700
+ uint renderingLayers = skinned.renderingLayerMask;
701
+ int sortingLayer = skinned.sortingLayerID, sortingOrder = skinned.sortingOrder;
702
+ // Unity allows one Renderer per GameObject: the skinned one must go before the MeshRenderer can be added.
703
+ UnityEngine.Object.DestroyImmediate(skinned);
704
+ // Unity's missing-component result is a fake null that `??` does not see, so compare explicitly.
705
+ var filter = gameObject.GetComponent<MeshFilter>();
706
+ if (filter == null) filter = gameObject.AddComponent<MeshFilter>();
707
+ filter.sharedMesh = mesh;
708
+ var meshRenderer = gameObject.AddComponent<MeshRenderer>();
709
+ meshRenderer.sharedMaterials = materials;
710
+ meshRenderer.shadowCastingMode = shadowCasting;
711
+ meshRenderer.receiveShadows = receiveShadows;
712
+ meshRenderer.lightProbeUsage = probeUsage;
713
+ meshRenderer.reflectionProbeUsage = reflectionUsage;
714
+ meshRenderer.probeAnchor = probeAnchor;
715
+ meshRenderer.motionVectorGenerationMode = motionVectors;
716
+ meshRenderer.allowOcclusionWhenDynamic = allowOcclusion;
717
+ meshRenderer.renderingLayerMask = renderingLayers;
718
+ meshRenderer.sortingLayerID = sortingLayer;
719
+ meshRenderer.sortingOrder = sortingOrder;
720
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
721
+ meshRenderer.enabled = wasEnabled;
722
+ EditorUtility.SetDirty(gameObject);
723
+ }
724
+
373
725
  /// <summary>
374
726
  /// Runtime point / spot lights that nothing in the browser drives become Baked: their direct light and shadows move
375
727
  /// into the lightmaps (static objects) and light probes (dynamic objects), and they cost nothing per frame. A light a
@@ -461,18 +813,29 @@ public static class BtOptimize
461
813
  var lod = renderer.GetComponentInParent<LODGroup>();
462
814
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
463
815
  bool lightmappable = level <= 0 && HasUV2(renderer) && VertexAnimationOf(renderer) == null && !IsTransparent(renderer);
816
+ bool keptOutOfBake = lightmappable && WithheldFromBake(path, context, options);
817
+ bool contributesGI = lightmappable && !keptOutOfBake;
818
+ bool keepInstanceable = IsRepeatedForInstancing(renderer, context, options);
464
819
  var newFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.ReflectionProbeStatic;
465
- if (lightmappable) newFlags |= StaticEditorFlags.ContributeGI;
820
+ if (contributesGI)
821
+ {
822
+ newFlags |= StaticEditorFlags.ContributeGI;
823
+ context.PlannedGIContributors.Add(path);
824
+ }
466
825
  var receive = renderer.receiveGI;
467
- var newReceive = lightmappable || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)) ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
826
+ // A repeated prop still contributes bounce light, but stays probe-lit so its copies share one instanced draw.
827
+ bool receivesLightmaps = !keepInstanceable && (contributesGI || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)));
828
+ var newReceive = receivesLightmaps ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
468
829
  if (!options.dryRun)
469
830
  {
470
831
  GameObjectUtility.SetStaticEditorFlags(gameObject, newFlags);
471
832
  renderer.receiveGI = newReceive;
472
833
  EditorUtility.SetDirty(renderer);
473
834
  }
474
- changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (lightmappable ? "static + ContributeGI, " : "static, ") + newReceive,
475
- Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "") });
835
+ changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (contributesGI ? "static + ContributeGI, " : "static, ") + newReceive,
836
+ Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "")
837
+ + (keepInstanceable ? "; stays probe-lit — " + context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw" : "")
838
+ + (keptOutOfBake ? "; " + KeepGIReason : "") });
476
839
  }
477
840
  }
478
841
 
@@ -495,8 +858,13 @@ public static class BtOptimize
495
858
  string path = PathOf(renderer.transform);
496
859
  if (IsExcluded(renderer.transform, options.exclude)) continue;
497
860
  string reason = NotAVisibleSurface(renderer) ?? (!HasUV2(renderer) ? "no lightmap UVs (UV2)" : VertexAnimationOf(renderer) ?? (IsTransparent(renderer) ? "transparent" : null));
861
+ if (reason == null && IsRepeatedForInstancing(renderer, context, options))
862
+ reason = context.RepeatCounts[RepeatKey(renderer)] + " copies: stays probe-lit so they share one instanced draw (lightmapped copies are exported as separate meshes)";
863
+ bool addsContributeGI = !flags.HasFlag(StaticEditorFlags.ContributeGI);
864
+ if (reason == null && addsContributeGI && WithheldFromBake(path, context, options)) reason = KeepGIReason;
498
865
  if (reason != null) { kept.Add(new Change { Kind = "probe-lit", Path = path, Why = reason }); continue; }
499
- string before = (flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI, " : "no ContributeGI, ") + renderer.receiveGI;
866
+ string before = (addsContributeGI ? "no ContributeGI, " : "ContributeGI, ") + renderer.receiveGI;
867
+ context.PlannedGIContributors.Add(path);
500
868
  if (!options.dryRun)
501
869
  {
502
870
  GameObjectUtility.SetStaticEditorFlags(renderer.gameObject, flags | StaticEditorFlags.ContributeGI);
@@ -512,8 +880,15 @@ public static class BtOptimize
512
880
  {
513
881
  if (!HasUV2(lower)) continue;
514
882
  lowerLevels++;
883
+ // --keep-gi keeps a lower level's own Contribute GI too: the copy's contributor set stays the source's.
884
+ var lowerFlags = GameObjectUtility.GetStaticEditorFlags(lower.gameObject) | StaticEditorFlags.BatchingStatic;
885
+ if (!options.keepSourceGI)
886
+ {
887
+ lowerFlags &= ~StaticEditorFlags.ContributeGI;
888
+ context.PlannedGIContributors.Remove(PathOf(lower.transform));
889
+ }
515
890
  if (options.dryRun) continue;
516
- GameObjectUtility.SetStaticEditorFlags(lower.gameObject, GameObjectUtility.GetStaticEditorFlags(lower.gameObject) & ~StaticEditorFlags.ContributeGI | StaticEditorFlags.BatchingStatic);
891
+ GameObjectUtility.SetStaticEditorFlags(lower.gameObject, lowerFlags);
517
892
  lower.receiveGI = ReceiveGI.Lightmaps;
518
893
  EditorUtility.SetDirty(lower);
519
894
  }
@@ -523,6 +898,80 @@ public static class BtOptimize
523
898
  }
524
899
  }
525
900
 
901
+ /// <summary>
902
+ /// Every unlightmapped copy in a repeat group (instanceRepeatsFrom copies or more of one mesh + materials) gets
903
+ /// Light Probe Usage Off and Receive GI Light Probes, so its copies share one instanced draw: the toolkit loads every
904
+ /// node that carries light probe data as its own mesh (SceneManager.DeinstanceProbeLitNodes). Reflection Probe Usage
905
+ /// and Contribute GI stay as they are. Runs last of the renderer steps, so it sees what Lightmap probe-lit left
906
+ /// unlightmapped; in a dry run it also covers the skinned copies UnskinRigid plans to convert.
907
+ /// </summary>
908
+ private static void InstanceRepeats(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
909
+ {
910
+ var candidates = context.Renderers.OfType<MeshRenderer>().Cast<Renderer>().Concat(context.PlannedUnskinned);
911
+ foreach (var renderer in candidates)
912
+ {
913
+ if (!IsRepeatedForInstancing(renderer, context, options)) continue;
914
+ string path = PathOf(renderer.transform);
915
+ if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "probe-lit repeat", Path = path, Why = "--exclude" }); continue; }
916
+ var meshRenderer = renderer as MeshRenderer;
917
+ // A converted skinned renderer comes out Receive GI Light Probes (see ReplaceWithMeshRenderer).
918
+ var receive = meshRenderer != null ? meshRenderer.receiveGI : ReceiveGI.LightProbes;
919
+ bool lightmapped = receive == ReceiveGI.Lightmaps && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI);
920
+ if (lightmapped) continue;
921
+ if (renderer.lightProbeUsage == LightProbeUsage.Off && receive == ReceiveGI.LightProbes) continue;
922
+ changes.Add(new Change { Kind = "Light probes off (instancing)", Path = path,
923
+ Before = "Light Probes " + renderer.lightProbeUsage + ", Receive GI " + receive + (meshRenderer == null ? " (once unskinned)" : ""),
924
+ After = "Light Probes Off, Receive GI LightProbes, Reflection Probes " + renderer.reflectionProbeUsage,
925
+ Why = context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
926
+ + " (SceneManager.DeinstanceProbeLitNodes); the copies light from the scene's ambient instead of the nearest probe" });
927
+ if (options.dryRun || meshRenderer == null) continue;
928
+ meshRenderer.lightProbeUsage = LightProbeUsage.Off;
929
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
930
+ EditorUtility.SetDirty(meshRenderer);
931
+ }
932
+ }
933
+
934
+ /// <summary>
935
+ /// True when --keep-gi forbids Contribute GI on the object at this hierarchy path: it did not contribute GI in the
936
+ /// source scene, and adding it would pull the object into the re-bake (darkening the source's indirect light).
937
+ /// </summary>
938
+ private static bool WithheldFromBake(string path, Context context, TuneOptions options)
939
+ {
940
+ return options.keepSourceGI && !context.SourceGIContributors.Contains(path);
941
+ }
942
+
943
+ /// <summary>
944
+ /// The hierarchy paths of the renderers that contribute GI in this scene's source: the scene named in the report
945
+ /// folder's working-copy.txt, opened additively and closed again unsaved (an already open source is only read). A
946
+ /// scene without that record (a dry run on the source itself) is its own source.
947
+ /// </summary>
948
+ private static HashSet<string> SourceGIContributorsOf(Scene scene, string reportFolder)
949
+ {
950
+ string recordPath = Path.Combine(reportFolder, "working-copy.txt");
951
+ string sourcePath = File.Exists(recordPath) ? File.ReadAllText(recordPath).Trim() : scene.path;
952
+ if (sourcePath == scene.path) return GIContributorPaths(scene.GetRootGameObjects());
953
+ var openSource = SceneManager.GetSceneByPath(sourcePath);
954
+ if (openSource.isLoaded) return GIContributorPaths(openSource.GetRootGameObjects());
955
+ var source = EditorSceneManager.OpenScene(sourcePath, OpenSceneMode.Additive);
956
+ try
957
+ {
958
+ return GIContributorPaths(source.GetRootGameObjects());
959
+ }
960
+ finally
961
+ {
962
+ EditorSceneManager.CloseScene(source, true);
963
+ }
964
+ }
965
+
966
+ /// <summary>The hierarchy paths of the active, enabled MeshRenderers under the roots whose objects have Contribute GI.</summary>
967
+ private static HashSet<string> GIContributorPaths(IEnumerable<GameObject> roots)
968
+ {
969
+ return new HashSet<string>(roots.SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(true))
970
+ .Where(renderer => renderer.enabled && renderer.gameObject.activeInHierarchy)
971
+ .Where(renderer => GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI))
972
+ .Select(renderer => PathOf(renderer.transform)));
973
+ }
974
+
526
975
  /// <summary>
527
976
  /// A motion blur override with intensity 0 does nothing in Unity (MotionBlur.IsActive() is false), but older
528
977
  /// toolkit runtimes still build a motion blur post-process and the buffers it needs. Deactivating the override
@@ -725,6 +1174,574 @@ public static class BtOptimize
725
1174
  return false;
726
1175
  }
727
1176
 
1177
+ // ------------------------------------------------------------------------------------------------------------
1178
+ // Skinning and repeats
1179
+ // ------------------------------------------------------------------------------------------------------------
1180
+
1181
+ /// <summary>
1182
+ /// What a skinned renderer really needs: one of the Skin* verdicts and the evidence. For a rigid mesh, also the
1183
+ /// fixed matrix that takes its mesh vertices to where the skinning draws them, in the object's local space.
1184
+ /// </summary>
1185
+ private sealed class SkinningVerdict
1186
+ {
1187
+ public string Kind, Why;
1188
+ /// <summary>True when the bind pose places the mesh farther from its object than the rest-pose tolerance; MeshToObject and MeshToWorld are then set.</summary>
1189
+ public bool OffsetBaked;
1190
+ public Matrix4x4 MeshToObject = Matrix4x4.identity;
1191
+ /// <summary>Where the skinning draws the mesh: bone × bind pose (mesh space to world space).</summary>
1192
+ public Matrix4x4 MeshToWorld = Matrix4x4.identity;
1193
+ public SkinningVerdict(string kind, string why) { Kind = kind; Why = why; }
1194
+ }
1195
+
1196
+ /// <summary>
1197
+ /// Decides whether a SkinnedMeshRenderer needs skinning, from what actually deforms it: its weighted bones, blend
1198
+ /// shapes and cloth, and which transforms animation clips, Timeline or browser scripts move. An Animator alone
1199
+ /// decides nothing — most props' Animators only move, scale or toggle the object as a whole.
1200
+ /// </summary>
1201
+ private static SkinningVerdict ClassifySkinning(SkinnedMeshRenderer renderer, Context context)
1202
+ {
1203
+ var mesh = renderer.sharedMesh;
1204
+ if (mesh == null) return new SkinningVerdict(SkinDeforms, "no mesh");
1205
+ if (mesh.blendShapeCount > 0) return new SkinningVerdict(SkinDeforms, mesh.blendShapeCount + " blend shapes");
1206
+ if (renderer.GetComponent<Cloth>() != null) return new SkinningVerdict(SkinDeforms, "Cloth");
1207
+ var bones = renderer.bones;
1208
+ var weightedBoneIndices = WeightedBoneIndices(renderer);
1209
+ if (weightedBoneIndices.Count > 1)
1210
+ {
1211
+ string movedBone = weightedBoneIndices.Select(index => SeparateMotionBetween(bones[index], renderer.transform, context)).FirstOrDefault(motion => motion != null);
1212
+ if (movedBone != null) return new SkinningVerdict(SkinDeforms, weightedBoneIndices.Count + " weighted bones; " + movedBone);
1213
+ string poseBlocker = ConversionBlocker(renderer, context);
1214
+ return poseBlocker != null
1215
+ ? new SkinningVerdict(SkinRigidByHand, weightedBoneIndices.Count + " weighted bones that never move, but " + poseBlocker)
1216
+ : new SkinningVerdict(SkinFrozenPose, weightedBoneIndices.Count + " weighted bones, none moved by a clip, Timeline or script");
1217
+ }
1218
+ if (weightedBoneIndices.Count == 0 || mesh.bindposes.Length <= weightedBoneIndices[0]) return new SkinningVerdict(SkinRigidByHand, "no usable bone weights or bind poses");
1219
+ int boneIndex = weightedBoneIndices[0];
1220
+ var bone = bones[boneIndex];
1221
+ string separateMotion = SeparateMotionBetween(bone, renderer.transform, context);
1222
+ bool scriptHost = separateMotion != null && IsOnlyScriptOnRenderer(renderer, bone, context);
1223
+ if (separateMotion != null && !scriptHost) return new SkinningVerdict(SkinRigidByHand, "one bone, but it may move apart from the object (" + separateMotion + "): parent a plain mesh under '" + bone.name + "'");
1224
+ string blocker = ConversionBlocker(renderer, context);
1225
+ if (blocker != null) return new SkinningVerdict(SkinRigidByHand, "one bone ('" + bone.name + "'), but " + blocker);
1226
+ string curveNote = context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve) ? "; a clip animates the SkinnedMeshRenderer itself (" + curve + ")" : "";
1227
+ if (scriptHost) return new SkinningVerdict(SkinRigidScriptHost, "one bone ('" + bone.name + "'); the only separate motion is " + separateMotion + ", on the renderer's own object" + curveNote);
1228
+ // A one-bone vertex is drawn at bone × bindpose × vertex; a MeshFilter draws it at object × vertex. The fixed
1229
+ // difference between the two, in the object's space, is all the skinning does.
1230
+ var meshToWorld = bone.localToWorldMatrix * mesh.bindposes[boneIndex];
1231
+ var meshToObject = renderer.transform.worldToLocalMatrix * meshToWorld;
1232
+ float offset = LargestVertexOffset(mesh, meshToObject, renderer.transform.lossyScale);
1233
+ bool offsetBaked = offset > RestPoseTolerance(renderer);
1234
+ string evidence = "one bone ('" + bone.name + "') moving with the object, no blend shapes or cloth"
1235
+ + (offsetBaked ? "; the bind pose offsets the mesh by up to " + offset.ToString("0.###") + " units" : ", bind pose within " + offset.ToString("0.####") + " units");
1236
+ string kind = offsetBaked ? SkinRigidOffset : SkinRigid;
1237
+ if (curveNote.Length > 0) kind = SkinRigidRendererCurves;
1238
+ var verdict = new SkinningVerdict(kind, evidence + curveNote) { OffsetBaked = offsetBaked };
1239
+ if (!offsetBaked) return verdict;
1240
+ verdict.MeshToObject = meshToObject;
1241
+ verdict.MeshToWorld = meshToWorld;
1242
+ return verdict;
1243
+ }
1244
+
1245
+ /// <summary>
1246
+ /// Why a skinned renderer whose bones move with it still cannot be converted automatically, or null: a component
1247
+ /// references the SkinnedMeshRenderer itself, or a clip Tune cannot retarget animates it.
1248
+ /// </summary>
1249
+ private static string ConversionBlocker(SkinnedMeshRenderer renderer, Context context)
1250
+ {
1251
+ if (context.ReferencedComponents.Contains(renderer)) return "a component references the SkinnedMeshRenderer itself";
1252
+ return RendererCurveBlocker(renderer, context);
1253
+ }
1254
+
1255
+ /// <summary>
1256
+ /// Why the clips that animate this SkinnedMeshRenderer cannot be retargeted to MeshRenderer, or null (also when no
1257
+ /// clip animates it). Only an Animator playing a plain AnimatorController can be given a retargeted copy.
1258
+ /// </summary>
1259
+ private static string RendererCurveBlocker(SkinnedMeshRenderer renderer, Context context)
1260
+ {
1261
+ if (!context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve)) return null;
1262
+ foreach (var animation in renderer.GetComponentsInParent<Animation>(true))
1263
+ if (AnimationUtility.GetAnimationClips(animation.gameObject).Any(clip => AnimatesRenderer(clip, animation.transform, renderer.transform)))
1264
+ return "a legacy Animation on '" + animation.name + "' animates it (" + curve + "): retarget the curve to MeshRenderer by hand";
1265
+ foreach (var animator in renderer.GetComponentsInParent<Animator>(true))
1266
+ {
1267
+ var controller = animator.runtimeAnimatorController;
1268
+ if (controller == null || controller is UnityEditor.Animations.AnimatorController) continue;
1269
+ if (controller.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, renderer.transform)))
1270
+ return "the Animator on '" + animator.name + "' animates it through a " + controller.GetType().Name + " (" + curve + "): retarget the curve to MeshRenderer by hand";
1271
+ }
1272
+ return null;
1273
+ }
1274
+
1275
+ /// <summary>
1276
+ /// True when the only separate motion between the bone and the renderer's object is a toolkit script on that object
1277
+ /// itself: no clip, Timeline, constraint, Rigidbody or script on either chain up to their common ancestor, and the
1278
+ /// renderer's own object has an EditorScriptComponent but is not animated and has no constraint or Rigidbody.
1279
+ /// </summary>
1280
+ private static bool IsOnlyScriptOnRenderer(SkinnedMeshRenderer renderer, Transform bone, Context context)
1281
+ {
1282
+ var rendererTransform = renderer.transform;
1283
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
1284
+ if (rendererTransform == commonAncestor) return false;
1285
+ var otherLinks = ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform.parent, commonAncestor));
1286
+ if (otherLinks.Any(node => MotionOn(node, context) != null)) return false;
1287
+ if (context.AnimatedTransforms.ContainsKey(rendererTransform)) return false;
1288
+ var components = rendererTransform.GetComponents<Component>();
1289
+ bool hasScript = components.Any(component => component is EditorScriptComponent);
1290
+ bool hasPhysicsOrConstraint = components.Any(component => component is Rigidbody || component is UnityEngine.Animations.IConstraint);
1291
+ return hasScript && !hasPhysicsOrConstraint;
1292
+ }
1293
+
1294
+ /// <summary>How far, in world units, a converted vertex may land from where the skinning drew it.</summary>
1295
+ private static float RestPoseTolerance(Renderer renderer)
1296
+ {
1297
+ return Mathf.Max(RestPoseToleranceUnits, renderer.bounds.size.magnitude * RestPoseRelativeTolerance);
1298
+ }
1299
+
1300
+ /// <summary>
1301
+ /// True when the renderer's object can simply be moved to where the skinning draws the mesh: a leaf with nothing on
1302
+ /// it but its Transform and renderer, that no clip animates and nothing references. Moving it keeps the original
1303
+ /// mesh, so every copy still shares one mesh (and one instanced draw).
1304
+ /// </summary>
1305
+ private static bool CanReseatObject(SkinnedMeshRenderer renderer, Context context)
1306
+ {
1307
+ var transform = renderer.transform;
1308
+ if (transform.childCount > 0 || context.AnimatedTransforms.ContainsKey(transform) || context.Referencers.ContainsKey(renderer.gameObject)) return false;
1309
+ return renderer.GetComponents<Component>().All(component => component is Transform || component is SkinnedMeshRenderer);
1310
+ }
1311
+
1312
+ /// <summary>
1313
+ /// Moves the object so its transform equals `meshToWorld`, then checks every vertex lands where the skinning drew
1314
+ /// it. Restores the old pose and returns false when it cannot (shear, a parent's non-uniform scale under rotation).
1315
+ /// </summary>
1316
+ private static bool TryReseatObject(Transform transform, Mesh mesh, Matrix4x4 meshToWorld, float tolerance)
1317
+ {
1318
+ Vector3 oldPosition = transform.localPosition, oldScale = transform.localScale;
1319
+ Quaternion oldRotation = transform.localRotation;
1320
+ var parentScale = transform.parent != null ? transform.parent.lossyScale : Vector3.one;
1321
+ var targetScale = meshToWorld.lossyScale;
1322
+ transform.SetPositionAndRotation(meshToWorld.GetPosition(), meshToWorld.rotation);
1323
+ transform.localScale = new Vector3(targetScale.x / parentScale.x, targetScale.y / parentScale.y, targetScale.z / parentScale.z);
1324
+ var placed = transform.localToWorldMatrix;
1325
+ bool matches = mesh.vertices.All(vertex => Vector3.Distance(placed.MultiplyPoint3x4(vertex), meshToWorld.MultiplyPoint3x4(vertex)) <= tolerance);
1326
+ if (matches) return true;
1327
+ transform.localPosition = oldPosition;
1328
+ transform.localRotation = oldRotation;
1329
+ transform.localScale = oldScale;
1330
+ return false;
1331
+ }
1332
+
1333
+ /// <summary>The indices of the bones that carry any vertex weight.</summary>
1334
+ private static List<int> WeightedBoneIndices(SkinnedMeshRenderer renderer)
1335
+ {
1336
+ var bones = renderer.bones;
1337
+ var weightedIndices = new HashSet<int>();
1338
+ foreach (var weight in renderer.sharedMesh.GetAllBoneWeights())
1339
+ if (weight.weight > 0f) weightedIndices.Add(weight.boneIndex);
1340
+ return weightedIndices.Where(index => index >= 0 && index < bones.Length && bones[index] != null).OrderBy(index => index).ToList();
1341
+ }
1342
+
1343
+ /// <summary>The largest distance, in world units, that the matrix moves any vertex of the mesh.</summary>
1344
+ private static float LargestVertexOffset(Mesh mesh, Matrix4x4 meshToObject, Vector3 objectScale)
1345
+ {
1346
+ float largest = 0f;
1347
+ foreach (var vertex in mesh.vertices)
1348
+ largest = Mathf.Max(largest, Vector3.Scale(meshToObject.MultiplyPoint3x4(vertex) - vertex, objectScale).magnitude);
1349
+ return largest;
1350
+ }
1351
+
1352
+ /// <summary>
1353
+ /// A plain copy of a rigid skinned mesh with its fixed bind-pose offset applied to positions, normals and
1354
+ /// tangents (winding flipped when the offset mirrors), saved once per mesh and offset so every copy shares it.
1355
+ /// </summary>
1356
+ private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
1357
+ {
1358
+ string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1359
+ string cacheKey = source.GetHashCode() + "|" + offsetKey;
1360
+ if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
1361
+ var baked = UnityEngine.Object.Instantiate(source);
1362
+ baked.name = source.name + "_Unskinned_" + bakedMeshes.Count;
1363
+ var normalMatrix = meshToObject.inverse.transpose;
1364
+ float handedness = meshToObject.determinant < 0f ? -1f : 1f;
1365
+ baked.vertices = source.vertices.Select(vertex => meshToObject.MultiplyPoint3x4(vertex)).ToArray();
1366
+ if (source.normals.Length > 0) baked.normals = source.normals.Select(normal => normalMatrix.MultiplyVector(normal).normalized).ToArray();
1367
+ if (source.tangents.Length > 0)
1368
+ baked.tangents = source.tangents.Select(tangent =>
1369
+ {
1370
+ var direction = meshToObject.MultiplyVector(new Vector3(tangent.x, tangent.y, tangent.z)).normalized;
1371
+ return new Vector4(direction.x, direction.y, direction.z, tangent.w * handedness);
1372
+ }).ToArray();
1373
+ if (handedness < 0f)
1374
+ for (int subMesh = 0; subMesh < baked.subMeshCount; subMesh++)
1375
+ baked.SetTriangles(baked.GetTriangles(subMesh).Reverse().ToArray(), subMesh);
1376
+ baked.boneWeights = new BoneWeight[0];
1377
+ baked.bindposes = new Matrix4x4[0];
1378
+ baked.RecalculateBounds();
1379
+ CreateMeshAsset(baked, folder);
1380
+ bakedMeshes[cacheKey] = baked;
1381
+ return baked;
1382
+ }
1383
+
1384
+ /// <summary>
1385
+ /// Folder for meshes baked from skinned meshes (offset rigid meshes and baked poses): &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1386
+ /// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
1387
+ /// </summary>
1388
+ private static string UnskinnedMeshFolder(Scene scene)
1389
+ {
1390
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_UnskinnedMeshes";
1391
+ }
1392
+
1393
+ /// <summary>Folder for clips and controllers copied with their SkinnedMeshRenderer curves retargeted: &lt;scene folder&gt;/&lt;scene&gt;_RetargetedClips.</summary>
1394
+ private static string RetargetedClipFolder(Scene scene)
1395
+ {
1396
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_RetargetedClips";
1397
+ }
1398
+
1399
+ /// <summary>Creates the project folder (one level below an existing folder) when it is missing.</summary>
1400
+ private static void EnsureFolder(string folder)
1401
+ {
1402
+ if (!AssetDatabase.IsValidFolder(folder)) AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), Path.GetFileName(folder));
1403
+ }
1404
+
1405
+ /// <summary>Saves the mesh as a new asset named after it in the folder (a unique path when the name is taken).</summary>
1406
+ private static void CreateMeshAsset(Mesh mesh, string folder)
1407
+ {
1408
+ EnsureFolder(folder);
1409
+ AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + mesh.name + ".asset"));
1410
+ }
1411
+
1412
+ /// <summary>
1413
+ /// The renderer's current skinned shape as a plain mesh in its object's space, shared by every renderer with the same
1414
+ /// source mesh and baked vertices (rounded to SharedMeshKeyDecimals) so the copies still instance. Saved in the
1415
+ /// folder unless `save` is false (a dry run, which only compares shapes; see DiscardUnsavedMeshes).
1416
+ /// </summary>
1417
+ private static Mesh BakedPoseMesh(SkinnedMeshRenderer skinned, string folder, Dictionary<string, Mesh> bakedMeshes, bool save, out string howPlaced)
1418
+ {
1419
+ var source = skinned.sharedMesh;
1420
+ var baked = BakePoseToObjectSpace(skinned);
1421
+ string shapeKey = PoseShapeKey(source, baked);
1422
+ if (bakedMeshes.TryGetValue(shapeKey, out var existing))
1423
+ {
1424
+ UnityEngine.Object.DestroyImmediate(baked);
1425
+ baked = existing;
1426
+ }
1427
+ else
1428
+ {
1429
+ string namePrefix = source.name + "_Pose_";
1430
+ baked.name = namePrefix + bakedMeshes.Values.Count(mesh => mesh.name.StartsWith(namePrefix, StringComparison.Ordinal));
1431
+ if (save) CreateMeshAsset(baked, folder);
1432
+ bakedMeshes[shapeKey] = baked;
1433
+ }
1434
+ string assetPath = EditorUtility.IsPersistent(baked) ? AssetDatabase.GetAssetPath(baked) : folder + "/" + baked.name + ".asset";
1435
+ howPlaced = "baked pose, shared mesh asset " + assetPath;
1436
+ return baked;
1437
+ }
1438
+
1439
+ /// <summary>
1440
+ /// A copy of the renderer's mesh with linear-blend skinning applied at the current bone pose, expressed in the
1441
+ /// renderer object's local space (what a MeshFilter on that object must draw), with the skin data removed. A vertex
1442
+ /// with no weights keeps its position.
1443
+ /// </summary>
1444
+ private static Mesh BakePoseToObjectSpace(SkinnedMeshRenderer skinned)
1445
+ {
1446
+ var source = skinned.sharedMesh;
1447
+ var boneToObject = BoneToObjectMatrices(skinned);
1448
+ var normalMatrices = boneToObject.Select(matrix => matrix.inverse.transpose).ToArray();
1449
+ var bonesPerVertex = source.GetBonesPerVertex();
1450
+ var weights = source.GetAllBoneWeights();
1451
+ var vertices = source.vertices;
1452
+ var normals = source.normals;
1453
+ var tangents = source.tangents;
1454
+ int weightIndex = 0;
1455
+ for (int i = 0; i < vertices.Length; i++)
1456
+ {
1457
+ Vector3 position = Vector3.zero, normal = Vector3.zero, tangent = Vector3.zero;
1458
+ int influenceCount = bonesPerVertex[i];
1459
+ for (int j = 0; j < influenceCount; j++, weightIndex++)
1460
+ {
1461
+ var influence = weights[weightIndex];
1462
+ position += influence.weight * boneToObject[influence.boneIndex].MultiplyPoint3x4(vertices[i]);
1463
+ if (normals.Length > 0) normal += influence.weight * normalMatrices[influence.boneIndex].MultiplyVector(normals[i]);
1464
+ if (tangents.Length > 0) tangent += influence.weight * boneToObject[influence.boneIndex].MultiplyVector(tangents[i]);
1465
+ }
1466
+ if (influenceCount == 0) continue;
1467
+ vertices[i] = position;
1468
+ if (normals.Length > 0) normals[i] = normal.normalized;
1469
+ if (tangents.Length > 0)
1470
+ {
1471
+ var direction = tangent.normalized;
1472
+ tangents[i] = new Vector4(direction.x, direction.y, direction.z, tangents[i].w);
1473
+ }
1474
+ }
1475
+ var baked = UnityEngine.Object.Instantiate(source);
1476
+ baked.boneWeights = new BoneWeight[0];
1477
+ baked.bindposes = new Matrix4x4[0];
1478
+ baked.vertices = vertices;
1479
+ if (normals.Length > 0) baked.normals = normals;
1480
+ if (tangents.Length > 0) baked.tangents = tangents;
1481
+ baked.RecalculateBounds();
1482
+ return baked;
1483
+ }
1484
+
1485
+ /// <summary>For each bone: object-from-world × bone-to-world × bind pose (identity for a missing bone or bind pose).</summary>
1486
+ private static Matrix4x4[] BoneToObjectMatrices(SkinnedMeshRenderer skinned)
1487
+ {
1488
+ var bones = skinned.bones;
1489
+ var bindposes = skinned.sharedMesh.bindposes;
1490
+ var worldToObject = skinned.transform.worldToLocalMatrix;
1491
+ var matrices = new Matrix4x4[bones.Length];
1492
+ for (int i = 0; i < bones.Length; i++)
1493
+ matrices[i] = bones[i] != null && i < bindposes.Length ? worldToObject * bones[i].localToWorldMatrix * bindposes[i] : Matrix4x4.identity;
1494
+ return matrices;
1495
+ }
1496
+
1497
+ /// <summary>Identifies a baked shape: the source mesh plus its vertex positions rounded to SharedMeshKeyDecimals.</summary>
1498
+ private static string PoseShapeKey(Mesh source, Mesh baked)
1499
+ {
1500
+ string format = "F" + SharedMeshKeyDecimals;
1501
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
1502
+ var rounded = baked.vertices.Select(vertex => vertex.x.ToString(format, culture) + "," + vertex.y.ToString(format, culture) + "," + vertex.z.ToString(format, culture));
1503
+ return "pose|" + source.GetHashCode() + "|" + string.Join(";", rounded).GetHashCode();
1504
+ }
1505
+
1506
+ // ------------------------------------------------------------------------------------------------------------
1507
+ // Renderer curves — clips that animate a SkinnedMeshRenderer, retargeted to the MeshRenderer that replaces it
1508
+ // ------------------------------------------------------------------------------------------------------------
1509
+
1510
+ /// <summary>The clip's float and object-reference curve bindings that target a SkinnedMeshRenderer.</summary>
1511
+ private static List<EditorCurveBinding> RendererBindings(AnimationClip clip)
1512
+ {
1513
+ return AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip))
1514
+ .Where(binding => binding.type == typeof(SkinnedMeshRenderer)).ToList();
1515
+ }
1516
+
1517
+ /// <summary>The transform a curve binding targets, resolved from the animated root, or null.</summary>
1518
+ private static Transform ResolveBinding(Transform animatedRoot, EditorCurveBinding binding)
1519
+ {
1520
+ return binding.path == "" ? animatedRoot : animatedRoot.Find(binding.path);
1521
+ }
1522
+
1523
+ /// <summary>True when the clip, played from the animated root, animates the SkinnedMeshRenderer on the target.</summary>
1524
+ private static bool AnimatesRenderer(AnimationClip clip, Transform animatedRoot, Transform target)
1525
+ {
1526
+ return clip != null && RendererBindings(clip).Any(binding => ResolveBinding(animatedRoot, binding) == target);
1527
+ }
1528
+
1529
+ /// <summary>The Animators on or above the renderer whose controller's clips animate that SkinnedMeshRenderer.</summary>
1530
+ private static List<Animator> AnimatorsWithRendererCurves(SkinnedMeshRenderer skinned)
1531
+ {
1532
+ return skinned.GetComponentsInParent<Animator>(true)
1533
+ .Where(animator => animator.runtimeAnimatorController is UnityEditor.Animations.AnimatorController)
1534
+ .Where(animator => animator.runtimeAnimatorController.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, skinned.transform)))
1535
+ .ToList();
1536
+ }
1537
+
1538
+ /// <summary>Names, for the report, each clip that will be copied with its curves retargeted and the controller copy that plays it.</summary>
1539
+ private static string RetargetPlan(List<Animator> animators, Transform target, string folder)
1540
+ {
1541
+ var plans = animators.Select(animator =>
1542
+ {
1543
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
1544
+ var clipNames = controller.animationClips.Where(clip => AnimatesRenderer(clip, animator.transform, target)).Select(clip => "'" + clip.name + "'").Distinct();
1545
+ return "clip " + string.Join(", ", clipNames) + " copied with its SkinnedMeshRenderer curves aimed at MeshRenderer, played by controller copy "
1546
+ + RetargetedControllerPath(controller, folder) + " (Animator on " + animator.name + ")";
1547
+ });
1548
+ return string.Join("; ", plans);
1549
+ }
1550
+
1551
+ /// <summary>Where the retargeted copy of a controller is saved.</summary>
1552
+ private static string RetargetedControllerPath(UnityEditor.Animations.AnimatorController controller, string folder)
1553
+ {
1554
+ return folder + "/" + controller.name + "_MeshRenderer.controller";
1555
+ }
1556
+
1557
+ /// <summary>
1558
+ /// Gives each Animator a copy of its controller whose clips aim every SkinnedMeshRenderer curve at a converted object
1559
+ /// (one that now has a MeshRenderer) at MeshRenderer instead, same path and property. Animators sharing a controller
1560
+ /// share its copy. The original clips and controllers are never edited; only the Animators in this scene change.
1561
+ /// </summary>
1562
+ private static void RetargetAnimators(List<Animator> animators, string folder)
1563
+ {
1564
+ var controllerCopies = new Dictionary<UnityEditor.Animations.AnimatorController, UnityEditor.Animations.AnimatorController>();
1565
+ var clipCopies = new Dictionary<AnimationClip, AnimationClip>();
1566
+ foreach (var animator in animators)
1567
+ {
1568
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
1569
+ if (!controllerCopies.TryGetValue(controller, out var copy))
1570
+ {
1571
+ copy = RetargetedController(controller, animator.transform, folder, clipCopies);
1572
+ controllerCopies[controller] = copy;
1573
+ }
1574
+ animator.runtimeAnimatorController = copy;
1575
+ EditorUtility.SetDirty(animator);
1576
+ }
1577
+ }
1578
+
1579
+ /// <summary>
1580
+ /// A fresh copy of the controller (replacing a copy an earlier run left) with every clip that has retargeted curves
1581
+ /// swapped for its copy, in every state and blend tree of every layer.
1582
+ /// </summary>
1583
+ private static UnityEditor.Animations.AnimatorController RetargetedController(UnityEditor.Animations.AnimatorController controller, Transform animatedRoot,
1584
+ string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
1585
+ {
1586
+ EnsureFolder(folder);
1587
+ string copyPath = RetargetedControllerPath(controller, folder);
1588
+ AssetDatabase.DeleteAsset(copyPath);
1589
+ if (!AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(controller), copyPath)) throw new InvalidOperationException("Could not copy " + controller.name + " to " + copyPath);
1590
+ var copy = AssetDatabase.LoadAssetAtPath<UnityEditor.Animations.AnimatorController>(copyPath);
1591
+ var replacements = new Dictionary<AnimationClip, AnimationClip>();
1592
+ foreach (var clip in controller.animationClips.Where(clip => clip != null).Distinct())
1593
+ {
1594
+ var retargeted = RetargetedClip(clip, animatedRoot, folder, clipCopies);
1595
+ if (retargeted != null) replacements[clip] = retargeted;
1596
+ }
1597
+ foreach (var layer in copy.layers) ReplaceMotions(layer.stateMachine, replacements);
1598
+ EditorUtility.SetDirty(copy);
1599
+ return copy;
1600
+ }
1601
+
1602
+ /// <summary>
1603
+ /// A copy of the clip with every SkinnedMeshRenderer curve whose target now has a MeshRenderer retargeted to
1604
+ /// MeshRenderer (same path and property), saved in the folder as &lt;clip&gt;_MeshRenderer.anim (an earlier run's copy
1605
+ /// is updated in place). Null when the clip has no such curve. Each clip is copied once per run.
1606
+ /// </summary>
1607
+ private static AnimationClip RetargetedClip(AnimationClip clip, Transform animatedRoot, string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
1608
+ {
1609
+ if (clipCopies.TryGetValue(clip, out var done)) return done;
1610
+ var bindings = RendererBindings(clip).Where(binding => ResolveBinding(animatedRoot, binding) is Transform target && target.GetComponent<MeshRenderer>() != null).ToList();
1611
+ if (bindings.Count == 0) return null;
1612
+ var retargeted = UnityEngine.Object.Instantiate(clip);
1613
+ retargeted.name = clip.name + "_MeshRenderer";
1614
+ foreach (var binding in bindings) RetargetBinding(clip, retargeted, binding);
1615
+ string clipPath = folder + "/" + retargeted.name + ".anim";
1616
+ var previous = AssetDatabase.LoadAssetAtPath<AnimationClip>(clipPath);
1617
+ if (previous == null)
1618
+ {
1619
+ AssetDatabase.CreateAsset(retargeted, clipPath);
1620
+ }
1621
+ else
1622
+ {
1623
+ EditorUtility.CopySerialized(retargeted, previous);
1624
+ UnityEngine.Object.DestroyImmediate(retargeted);
1625
+ retargeted = previous;
1626
+ }
1627
+ clipCopies[clip] = retargeted;
1628
+ return retargeted;
1629
+ }
1630
+
1631
+ /// <summary>Moves one curve of the copied clip from the SkinnedMeshRenderer binding to the same MeshRenderer binding.</summary>
1632
+ private static void RetargetBinding(AnimationClip source, AnimationClip retargeted, EditorCurveBinding binding)
1633
+ {
1634
+ var meshBinding = binding;
1635
+ meshBinding.type = typeof(MeshRenderer);
1636
+ if (binding.isPPtrCurve)
1637
+ {
1638
+ var keyframes = AnimationUtility.GetObjectReferenceCurve(source, binding);
1639
+ AnimationUtility.SetObjectReferenceCurve(retargeted, binding, null);
1640
+ AnimationUtility.SetObjectReferenceCurve(retargeted, meshBinding, keyframes);
1641
+ return;
1642
+ }
1643
+ var curve = AnimationUtility.GetEditorCurve(source, binding);
1644
+ AnimationUtility.SetEditorCurve(retargeted, binding, null);
1645
+ AnimationUtility.SetEditorCurve(retargeted, meshBinding, curve);
1646
+ }
1647
+
1648
+ /// <summary>Swaps state motions in the state machine (and its sub-state machines) for their replacements.</summary>
1649
+ private static void ReplaceMotions(UnityEditor.Animations.AnimatorStateMachine stateMachine, Dictionary<AnimationClip, AnimationClip> replacements)
1650
+ {
1651
+ foreach (var child in stateMachine.states) child.state.motion = ReplacedMotion(child.state.motion, replacements);
1652
+ foreach (var child in stateMachine.stateMachines) ReplaceMotions(child.stateMachine, replacements);
1653
+ }
1654
+
1655
+ /// <summary>The motion with every replaced clip swapped in: the clip's replacement, or a blend tree with its children swapped.</summary>
1656
+ private static Motion ReplacedMotion(Motion motion, Dictionary<AnimationClip, AnimationClip> replacements)
1657
+ {
1658
+ if (motion is AnimationClip clip) return replacements.TryGetValue(clip, out var replacement) ? replacement : clip;
1659
+ if (!(motion is UnityEditor.Animations.BlendTree blendTree)) return motion;
1660
+ var children = blendTree.children;
1661
+ for (int i = 0; i < children.Length; i++) children[i].motion = ReplacedMotion(children[i].motion, replacements);
1662
+ blendTree.children = children;
1663
+ return blendTree;
1664
+ }
1665
+
1666
+ /// <summary>
1667
+ /// What moves the bone relative to the renderer's object, or null when the two always move together. Only the
1668
+ /// transforms between each of them and their nearest common ancestor count: whatever moves that ancestor (an
1669
+ /// Animator popping the whole prop in, a script spinning it) moves bone and mesh alike.
1670
+ /// </summary>
1671
+ private static string SeparateMotionBetween(Transform bone, Transform rendererTransform, Context context)
1672
+ {
1673
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
1674
+ return ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform, commonAncestor))
1675
+ .Select(node => MotionOn(node, context)).FirstOrDefault(motion => motion != null);
1676
+ }
1677
+
1678
+ /// <summary>The nearest transform that is the bone or one of its ancestors and also the renderer's object or one of its ancestors (null when none is).</summary>
1679
+ private static Transform CommonAncestor(Transform bone, Transform rendererTransform)
1680
+ {
1681
+ var rendererAncestors = new HashSet<Transform>();
1682
+ for (var node = rendererTransform; node != null; node = node.parent) rendererAncestors.Add(node);
1683
+ var commonAncestor = bone;
1684
+ while (commonAncestor != null && !rendererAncestors.Contains(commonAncestor)) commonAncestor = commonAncestor.parent;
1685
+ return commonAncestor;
1686
+ }
1687
+
1688
+ /// <summary>The transform and its ancestors up to, but not including, the ancestor (empty when start is null or the ancestor).</summary>
1689
+ private static IEnumerable<Transform> ChainBelow(Transform start, Transform ancestor)
1690
+ {
1691
+ for (var node = start; node != null && node != ancestor; node = node.parent) yield return node;
1692
+ }
1693
+
1694
+ /// <summary>What can move this one transform on its own — a clip or Timeline, a toolkit script, a Rigidbody or a constraint — or null.</summary>
1695
+ private static string MotionOn(Transform node, Context context)
1696
+ {
1697
+ if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return "'" + node.name + "' is animated by " + animator;
1698
+ foreach (var component in node.GetComponents<Component>())
1699
+ if (component is EditorScriptComponent || component is Rigidbody || component is UnityEngine.Animations.IConstraint)
1700
+ return "'" + node.name + "' has " + component.GetType().Name;
1701
+ return null;
1702
+ }
1703
+
1704
+ /// <summary>True when the renderer's mesh and materials repeat often enough that its copies should share an instanced draw.</summary>
1705
+ private static bool IsRepeatedForInstancing(Renderer renderer, Context context, TuneOptions options)
1706
+ {
1707
+ return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) && copies >= options.instanceRepeatsFrom;
1708
+ }
1709
+
1710
+ /// <summary>
1711
+ /// Identifies renderers that draw the same mesh with the same materials (the copies an instanced draw can share).
1712
+ /// Unity objects hash by identity, which works on every Editor version (GetInstanceID is obsolete in Unity 6.5).
1713
+ /// </summary>
1714
+ private static string RepeatKey(Renderer renderer)
1715
+ {
1716
+ var mesh = MeshOf(renderer);
1717
+ string meshKey = mesh != null ? mesh.GetHashCode().ToString() : "none";
1718
+ return meshKey + "|" + string.Join(",", renderer.sharedMaterials.Select(material => material != null ? material.GetHashCode() : 0));
1719
+ }
1720
+
1721
+ /// <summary>The mesh a Mesh or SkinnedMeshRenderer draws.</summary>
1722
+ private static Mesh MeshOf(Renderer renderer)
1723
+ {
1724
+ if (renderer is SkinnedMeshRenderer skinned) return skinned.sharedMesh;
1725
+ var filter = renderer.GetComponent<MeshFilter>();
1726
+ return filter != null ? filter.sharedMesh : null;
1727
+ }
1728
+
1729
+ /// <summary>Draw calls one copy costs per pass: one per submesh.</summary>
1730
+ private static int SubMeshCount(Renderer renderer)
1731
+ {
1732
+ var mesh = MeshOf(renderer);
1733
+ return mesh != null ? Mathf.Max(1, mesh.subMeshCount) : 1;
1734
+ }
1735
+
1736
+ /// <summary>The reflection probe that lights the renderer most (the exporter splits a material per probe), or "".</summary>
1737
+ private static string DominantReflectionProbe(Renderer renderer)
1738
+ {
1739
+ var probes = new List<ReflectionProbeBlendInfo>();
1740
+ renderer.GetClosestReflectionProbes(probes);
1741
+ var dominant = probes.OrderByDescending(probe => probe.weight).FirstOrDefault();
1742
+ return dominant.probe != null ? dominant.probe.name : "";
1743
+ }
1744
+
728
1745
  // ------------------------------------------------------------------------------------------------------------
729
1746
  // Helpers
730
1747
  // ------------------------------------------------------------------------------------------------------------
@@ -740,9 +1757,28 @@ public static class BtOptimize
740
1757
  public readonly HashSet<GameObject> TimelineBound;
741
1758
  /// <summary>Objects that toolkit script components (which run in the browser) point at.</summary>
742
1759
  public readonly Dictionary<GameObject, List<string>> WebReferencers;
1760
+ /// <summary>Transforms an animation clip (Animator / Animation) or a Timeline moves, with what moves them.</summary>
1761
+ public readonly Dictionary<Transform, string> AnimatedTransforms;
1762
+ /// <summary>Objects whose Renderer / SkinnedMeshRenderer a clip animates directly, with the curve.</summary>
1763
+ public readonly Dictionary<Transform, string> RendererCurveTargets;
1764
+ /// <summary>Components (not just GameObjects) a serialized field points at.</summary>
1765
+ public readonly HashSet<Component> ReferencedComponents;
1766
+ /// <summary>How many active renderers draw each mesh + materials combination (see RepeatKey).</summary>
1767
+ public readonly Dictionary<string, int> RepeatCounts;
1768
+ /// <summary>Hierarchy paths of the renderers that contribute GI in the source scene (Tune only; empty for a survey).</summary>
1769
+ public readonly HashSet<string> SourceGIContributors;
1770
+ /// <summary>
1771
+ /// Hierarchy paths of the renderers that contribute GI once Tune's changes land. Starts as the scene's own set;
1772
+ /// the steps keep it in step with the Contribute GI flags they add or clear, so a dry run can count it too.
1773
+ /// </summary>
1774
+ public readonly HashSet<string> PlannedGIContributors;
1775
+ /// <summary>Skinned renderers a dry run plans to convert: later steps treat them as the MeshRenderers they become.</summary>
1776
+ public readonly List<SkinnedMeshRenderer> PlannedUnskinned = new List<SkinnedMeshRenderer>();
743
1777
  public readonly StringBuilder Summary = new StringBuilder();
744
1778
 
745
- public Context(Scene scene)
1779
+ /// <param name="scene">The scene to gather.</param>
1780
+ /// <param name="sourceGIContributors">Tune's source contributor set (see SourceGIContributorsOf); null for a survey.</param>
1781
+ public Context(Scene scene, HashSet<string> sourceGIContributors = null)
746
1782
  {
747
1783
  Scene = scene;
748
1784
  Roots = scene.GetRootGameObjects().ToList();
@@ -751,6 +1787,13 @@ public static class BtOptimize
751
1787
  Referencers = CollectReferencers(Roots, false);
752
1788
  WebReferencers = CollectReferencers(Roots, true);
753
1789
  TimelineBound = CollectTimelineBindings(Roots);
1790
+ AnimatedTransforms = new Dictionary<Transform, string>();
1791
+ RendererCurveTargets = new Dictionary<Transform, string>();
1792
+ CollectAnimationTargets(this);
1793
+ ReferencedComponents = CollectReferencedComponents(Roots);
1794
+ RepeatCounts = Renderers.GroupBy(RepeatKey).ToDictionary(group => group.Key, group => group.Count());
1795
+ SourceGIContributors = sourceGIContributors ?? new HashSet<string>();
1796
+ PlannedGIContributors = GIContributorPaths(Roots);
754
1797
  }
755
1798
 
756
1799
  /// <summary>Every component of type T in the scene, including inactive objects.</summary>
@@ -881,6 +1924,57 @@ public static class BtOptimize
881
1924
  return result;
882
1925
  }
883
1926
 
1927
+ /// <summary>
1928
+ /// Fills the context's AnimatedTransforms (every transform a clip of an Animator or legacy Animation moves, plus
1929
+ /// every Timeline-bound object and its children) and RendererCurveTargets (objects whose renderer component a clip
1930
+ /// animates — converting that renderer would break the curve).
1931
+ /// </summary>
1932
+ private static void CollectAnimationTargets(Context context)
1933
+ {
1934
+ foreach (var root in context.Roots)
1935
+ {
1936
+ foreach (var animator in root.GetComponentsInChildren<Animator>(true))
1937
+ {
1938
+ var clips = animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.animationClips : new AnimationClip[0];
1939
+ AddClipTargets(context, animator.transform, clips, "Animator on " + animator.name);
1940
+ }
1941
+ foreach (var animation in root.GetComponentsInChildren<Animation>(true))
1942
+ AddClipTargets(context, animation.transform, AnimationUtility.GetAnimationClips(animation.gameObject), "Animation on " + animation.name);
1943
+ }
1944
+ foreach (var bound in context.TimelineBound)
1945
+ foreach (var node in bound.GetComponentsInChildren<Transform>(true))
1946
+ context.AnimatedTransforms[node] = "a Timeline track";
1947
+ }
1948
+
1949
+ /// <summary>Records what each clip's curves move, resolving curve paths from the animating object.</summary>
1950
+ private static void AddClipTargets(Context context, Transform animatedRoot, IEnumerable<AnimationClip> clips, string source)
1951
+ {
1952
+ foreach (var clip in clips.Where(clip => clip != null).Distinct())
1953
+ foreach (var binding in AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip)))
1954
+ {
1955
+ var target = binding.path == "" ? animatedRoot : animatedRoot.Find(binding.path);
1956
+ if (target == null) continue;
1957
+ if (binding.type == typeof(Transform)) context.AnimatedTransforms[target] = source + " (clip '" + clip.name + "')";
1958
+ else if (typeof(Renderer).IsAssignableFrom(binding.type)) context.RendererCurveTargets[target] = binding.type.Name + "." + binding.propertyName + " in '" + clip.name + "'";
1959
+ }
1960
+ }
1961
+
1962
+ /// <summary>Every component a serialized field in the scene points at directly (a GameObject reference does not count).</summary>
1963
+ private static HashSet<Component> CollectReferencedComponents(List<GameObject> roots)
1964
+ {
1965
+ var referenced = new HashSet<Component>();
1966
+ foreach (var root in roots)
1967
+ foreach (var component in root.GetComponentsInChildren<Component>(true))
1968
+ {
1969
+ if (component == null || component is Transform || component is MeshFilter || component is Renderer || component is LODGroup) continue;
1970
+ var property = new SerializedObject(component).GetIterator();
1971
+ while (property.Next(true))
1972
+ if (property.propertyType == SerializedPropertyType.ObjectReference && property.objectReferenceValue is Component target && target != component)
1973
+ referenced.Add(target);
1974
+ }
1975
+ return referenced;
1976
+ }
1977
+
884
1978
  /// <summary>Every GameObject bound to a track of a PlayableDirector in the scene.</summary>
885
1979
  private static HashSet<GameObject> CollectTimelineBindings(List<GameObject> roots)
886
1980
  {