@babylonjs-toolkit/agent 1.2.10 → 1.2.12

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.
@@ -36,18 +36,40 @@ public static class BtOptimize
36
36
  /// </summary>
37
37
  private const string SkinRigidOffset = "rigid — needs no skinning (offset baked)";
38
38
 
39
- /// <summary>Offset matrices are compared at this precision when copies share one baked mesh.</summary>
40
- private const int OffsetKeyDecimals = 4;
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
41
 
42
- /// <summary>Skinning verdict: rigid, but converting would change it (its bone moves on its own, or the bind pose differs).</summary>
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>
43
59
  private const string SkinRigidByHand = "rigid — convert by hand";
44
60
 
45
- /// <summary>Skinning verdict: several weighted bones that nothing animates — the pose never changes.</summary>
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>
46
65
  private const string SkinFrozenPose = "frozen pose — bake to a static mesh";
47
66
 
48
67
  /// <summary>Skinning verdict: really deforms (animated bones, blend shapes or cloth).</summary>
49
68
  private const string SkinDeforms = "deforms — really skinned";
50
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
+
51
73
  // ------------------------------------------------------------------------------------------------------------
52
74
  // Survey
53
75
  // ------------------------------------------------------------------------------------------------------------
@@ -72,6 +94,7 @@ public static class BtOptimize
72
94
  SurveyRenderers(context, md, json);
73
95
  SurveySkinning(context, md, json);
74
96
  SurveyRepeats(context, md, json);
97
+ SurveyShadowCasters(context, md, json);
75
98
  SurveyPostProcessing(context, md, json);
76
99
  SurveyPipeline(md, json);
77
100
  SurveyExporter(context, md, json);
@@ -218,8 +241,10 @@ public static class BtOptimize
218
241
  {
219
242
  if (verdictKind == SkinRigid) return "Tune converts it (unskinRigid)";
220
243
  if (verdictKind == SkinRigidOffset) return "Tune converts it to a shared baked mesh (unskinRigid)";
244
+ if (verdictKind == SkinRigidScriptHost) return "Tune bakes it to a plain mesh in place (unskinRigid)";
245
+ if (verdictKind == SkinRigidRendererCurves) return "Tune converts it and retargets the clip to MeshRenderer (unskinRigid)";
221
246
  if (verdictKind == SkinRigidByHand) return "convert by hand (see Why), then re-survey";
222
- if (verdictKind == SkinFrozenPose) return "bake each copy to a static mesh by hand (SkinnedMeshRenderer.BakeMesh), then re-survey";
247
+ if (verdictKind == SkinFrozenPose) return "Tune bakes it to a static mesh";
223
248
  return copies > 1 ? "repeated deforming mesh: candidate for the toolkit AnimatorControlRig VAT (crowd) mode — instanced, one draw" : "keep";
224
249
  }
225
250
 
@@ -273,9 +298,100 @@ public static class BtOptimize
273
298
  int lightmapped = renderers.OfType<MeshRenderer>().Count(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
274
299
  && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
275
300
  if (lightmapped > 0) blockers.Add("lightmapped ×" + lightmapped + " (each lightmapped copy is exported as its own mesh)");
301
+ int probeLit = renderers.OfType<MeshRenderer>().Count(renderer => renderer.lightProbeUsage != LightProbeUsage.Off && !(renderer.receiveGI == ReceiveGI.Lightmaps
302
+ && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI)));
303
+ if (probeLit > 0) blockers.Add("probe-lit ×" + probeLit + " (the toolkit loads each light-probe-lit node as its own mesh — SceneManager.DeinstanceProbeLitNodes; Tune turns probes off on repeats)");
276
304
  return blockers;
277
305
  }
278
306
 
307
+ /// <summary>Share of a renderer's surface area that faces up or down within this cosine (about 37°) to count as horizontal.</summary>
308
+ private const float HorizontalNormalCosine = 0.8f;
309
+
310
+ /// <summary>A shadow caster whose surface is at least this share horizontal is listed as a prune candidate.</summary>
311
+ private const float FlatCasterShare = 0.9f;
312
+
313
+ /// <summary>How many prune candidates the survey lists.</summary>
314
+ private const int MaxCasterCandidates = 40;
315
+
316
+ /// <summary>
317
+ /// Shadow casters that are probably pure cost: unique (not repeated), shadow-casting renderers whose surface is almost
318
+ /// all horizontal — roads, ground, markings, water and grass planes, undersides. A flat surface's shadow falls only
319
+ /// on what lies right under it, yet a directional light draws it again in every cascade it touches. These are
320
+ /// candidates only: an overhanging lip or a deck above other geometry does cast a visible shadow, so each one is
321
+ /// pruned (PruneShadowCasters) only when Unity captures at the pinned poses show no change. The browser's
322
+ /// per-cascade dump (`profile-browser.mjs --casters true`) adds far backdrops and gives each caster's draws.
323
+ /// </summary>
324
+ private static void SurveyShadowCasters(Context context, StringBuilder md, Dictionary<string, object> json)
325
+ {
326
+ var rows = new List<object>();
327
+ md.AppendLine("## Shadow casters — flat surfaces to prune (verify each by capture)");
328
+ md.AppendLine();
329
+ // Skinned meshes Tune converts to plain meshes (often whole DAE / FBX levels) are ground too; really skinned ones are characters.
330
+ var casters = context.Renderers
331
+ .Where(renderer => renderer is MeshRenderer || (renderer is SkinnedMeshRenderer skinned && TuneConverts(ClassifySkinning(skinned, context).Kind)))
332
+ .Where(renderer => renderer.shadowCastingMode == ShadowCastingMode.On || renderer.shadowCastingMode == ShadowCastingMode.TwoSided)
333
+ .Where(renderer => !context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) || copies == 1)
334
+ .Select(renderer => new { renderer, surface = HorizontalSurface(renderer) })
335
+ .Where(entry => entry.surface.TotalArea > 0f && entry.surface.HorizontalArea / entry.surface.TotalArea >= FlatCasterShare)
336
+ .OrderByDescending(entry => entry.surface.TotalArea)
337
+ .Take(MaxCasterCandidates)
338
+ .ToList();
339
+ int shadowCasting = context.Renderers.Count(renderer => renderer.shadowCastingMode != ShadowCastingMode.Off);
340
+ md.AppendLine("Shadow-casting renderers: **" + shadowCasting + "**. Flat candidates (≥ " + (FlatCasterShare * 100f).ToString("0") + "% of the surface horizontal): **" + casters.Count + "**.");
341
+ md.AppendLine();
342
+ if (casters.Count == 0) { md.AppendLine("None."); md.AppendLine(); json["shadowCasterCandidates"] = rows; return; }
343
+ md.AppendLine("| Renderer | Area (m²) | Horizontal | Static |");
344
+ md.AppendLine("|---|---|---|---|");
345
+ foreach (var entry in casters)
346
+ {
347
+ string path = PathOf(entry.renderer.transform);
348
+ float share = entry.surface.HorizontalArea / entry.surface.TotalArea;
349
+ bool isStatic = GameObjectUtility.GetStaticEditorFlags(entry.renderer.gameObject) != 0;
350
+ md.AppendLine("| " + path + " | " + entry.surface.TotalArea.ToString("0") + " | " + (share * 100f).ToString("0") + "% | " + (isStatic ? "yes" : "no") + " |");
351
+ rows.Add(new Dictionary<string, object> { { "path", path }, { "area", entry.surface.TotalArea }, { "horizontalShare", share }, { "static", isStatic } });
352
+ }
353
+ md.AppendLine();
354
+ context.Summary.AppendLine("shadowCasters=" + shadowCasting + " flatCandidates=" + casters.Count);
355
+ json["shadowCasterCandidates"] = rows;
356
+ }
357
+
358
+ /// <summary>A renderer's world-space surface area, and how much of it faces up or down (see HorizontalNormalCosine).</summary>
359
+ private struct SurfaceArea
360
+ {
361
+ public float TotalArea, HorizontalArea;
362
+ }
363
+
364
+ /// <summary>Measures the renderer's triangles in world space (a skinned mesh as its bones draw it now).</summary>
365
+ private static SurfaceArea HorizontalSurface(Renderer renderer)
366
+ {
367
+ var area = new SurfaceArea();
368
+ // Editor scripts read a mesh's vertices whatever its Read/Write import setting (the unskin step relies on it too).
369
+ var mesh = MeshOf(renderer);
370
+ if (mesh == null) return area;
371
+ Vector3[] localVertices;
372
+ if (renderer is SkinnedMeshRenderer skinned)
373
+ {
374
+ // BakeMesh writes the skinned shape in the renderer's space, without its scale (useScale false).
375
+ var posed = new Mesh();
376
+ skinned.BakeMesh(posed, false);
377
+ localVertices = posed.vertices;
378
+ UnityEngine.Object.DestroyImmediate(posed);
379
+ }
380
+ else localVertices = mesh.vertices;
381
+ var toWorld = renderer is SkinnedMeshRenderer ? Matrix4x4.TRS(renderer.transform.position, renderer.transform.rotation, Vector3.one) : renderer.transform.localToWorldMatrix;
382
+ var vertices = localVertices.Select(vertex => toWorld.MultiplyPoint3x4(vertex)).ToArray();
383
+ var triangles = mesh.triangles;
384
+ for (int i = 0; i + 2 < triangles.Length; i += 3)
385
+ {
386
+ var cross = Vector3.Cross(vertices[triangles[i + 1]] - vertices[triangles[i]], vertices[triangles[i + 2]] - vertices[triangles[i]]);
387
+ float triangleArea = cross.magnitude * 0.5f;
388
+ if (triangleArea <= 0f) continue;
389
+ area.TotalArea += triangleArea;
390
+ if (Mathf.Abs(cross.normalized.y) >= HorizontalNormalCosine) area.HorizontalArea += triangleArea;
391
+ }
392
+ return area;
393
+ }
394
+
279
395
  /// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
280
396
  private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
281
397
  {
@@ -320,6 +436,10 @@ public static class BtOptimize
320
436
  + " HDR=" + camera.allowHDR + " MSAA=" + camera.allowMSAA + " far=" + camera.farClipPlane);
321
437
  cameras.Add(new Dictionary<string, object> { { "path", PathOf(camera.transform) }, { "enabled", camera.isActiveAndEnabled }, { "antialiasing", aa }, { "antialiasingQuality", aaQuality }, { "postProcessing", post }, { "far", camera.farClipPlane } });
322
438
  }
439
+ int postCameras = cameras.Cast<Dictionary<string, object>>().Count(camera => (bool)camera["enabled"] && (string)camera["postProcessing"] == "True");
440
+ md.AppendLine();
441
+ md.AppendLine("Enabled cameras with post-processing: **" + postCameras + "**" + (postCameras > 1
442
+ ? " — each builds its own post chain in the browser; check the profile census's post passes, and turn post off on a camera that is not the one the player sees" : "") + ".");
323
443
  md.AppendLine();
324
444
  json["volumes"] = volumes;
325
445
  json["cameras"] = cameras;
@@ -421,7 +541,7 @@ public static class BtOptimize
421
541
  /// <summary>
422
542
  /// Also bake lights that cast realtime shadows. Off by default: a shadowed key light reaches past geometry its
423
543
  /// shadow map ignores (single-sided back faces, the near plane around its fixture) and the lightmapper does not —
424
- /// baked, Garden's room lights stayed trapped and the rooms went dark. Kept lights lose only their realtime shadows.
544
+ /// baked, a measured scene's room lights stayed trapped and the rooms went dark. Kept lights lose only their realtime shadows.
425
545
  /// </summary>
426
546
  public bool bakeShadowedLights = false;
427
547
  /// <summary>Light names (or prefixes ending in *) that stay as they are.</summary>
@@ -435,17 +555,38 @@ public static class BtOptimize
435
555
  /// </summary>
436
556
  public bool unskinRigid = true;
437
557
  /// <summary>
438
- /// A mesh drawn this many times or more (same mesh and materials) stays light-probe lit instead of being
439
- /// lightmapped, so the exporter can share one instanced draw across the copies (lightmapped copies never share).
440
- /// 0 turns the rule off.
558
+ /// A mesh drawn this many times or more (same mesh and materials) is not lightmapped (lightmapped copies never
559
+ /// share), and its copies get Light Probe Usage Off so they share one instanced draw: the toolkit loads every
560
+ /// probe-lit node as its own mesh (SceneManager.DeinstanceProbeLitNodes). 0 turns the rule off.
441
561
  /// </summary>
442
562
  public int instanceRepeatsFrom = 4;
563
+ /// <summary>
564
+ /// Keep Contribute GI exactly as the source scene has it (the source named in working-copy.txt): no step adds
565
+ /// Contribute GI to an object that did not contribute in the source, so the re-bake keeps the source's indirect
566
+ /// light. Off by default, because merging needs the newly lightmapped props.
567
+ /// </summary>
568
+ public bool keepSourceGI = false;
569
+ /// <summary>
570
+ /// Clear every static flag on objects that move in the browser although they are marked static: a clip or a
571
+ /// Timeline moves them (or an ancestor), or a physics body or navigation agent does. The exporter freezes a static
572
+ /// object's world matrix, so a static spinning prop would stand still (and a lightmap baked in one place is wrong
573
+ /// once it moves); they become probe-lit.
574
+ /// </summary>
575
+ public bool unfreezeAnimated = true;
443
576
  /// <summary>Mark renderers static when nothing in the browser can move them.</summary>
444
577
  public bool markStatic = true;
445
578
  /// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
446
579
  public bool lightmapProbeLit = true;
447
580
  /// <summary>Deactivate motion blur overrides whose intensity is 0 in the profiles this scene uses (a no-op in Unity).</summary>
448
581
  public bool fixZeroMotionBlur = true;
582
+ /// <summary>
583
+ /// A character that really deforms (bones a clip moves) and appears this many times or more (Animators whose
584
+ /// skinned renderers draw the same meshes) becomes a vertex-animation (VAT) crowd: the toolkit's
585
+ /// AnimatorControlRig in UseVertexAnimations mode, its materials copied onto the toolkit's vertex-animation shader,
586
+ /// its renderers at world scale 1 with Light Probes Off. The exporter bakes the clips to vertex animation textures
587
+ /// and the browser draws the copies instanced, each keeping its own Animator state. 0 turns the rule off.
588
+ /// </summary>
589
+ public int vatCrowdsFrom = 4;
449
590
  /// <summary>Object names (or prefixes ending in *) whose subtrees Tune never touches.</summary>
450
591
  public string[] exclude = new string[0];
451
592
  /// <summary>Plan only: report every change without making it (works on any scene, including the source).</summary>
@@ -469,7 +610,8 @@ public static class BtOptimize
469
610
  string folder = ReportFolder(scene);
470
611
  if (!options.dryRun && !File.Exists(Path.Combine(folder, "working-copy.txt")))
471
612
  throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; Tune never edits a source scene.");
472
- var context = new Context(scene);
613
+ var sourceGIContributors = SourceGIContributorsOf(scene, folder);
614
+ var context = new Context(scene, sourceGIContributors);
473
615
  var changes = new List<Change>();
474
616
  var kept = new List<Change>();
475
617
 
@@ -477,12 +619,19 @@ public static class BtOptimize
477
619
  {
478
620
  int converted = UnskinRigid(context, options, changes, kept);
479
621
  // The converted objects now have MeshRenderers: gather the scene again so the static and lightmap steps see them.
480
- if (converted > 0 && !options.dryRun) context = new Context(scene);
622
+ if (converted > 0 && !options.dryRun) context = new Context(scene, sourceGIContributors);
481
623
  }
624
+ if (options.unfreezeAnimated) UnfreezeAnimated(context, options, changes, kept);
482
625
  if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
483
626
  if (options.markStatic) MarkStatic(context, options, changes, kept);
484
627
  if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
628
+ if (options.instanceRepeatsFrom > 0) InstanceRepeats(context, options, changes, kept);
629
+ if (options.vatCrowdsFrom > 0) VatCrowds(context, options, changes, kept);
485
630
  if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
631
+ // A dry run changed no flags, so its copy count is the one the planned changes would leave.
632
+ int copyGIContributors = options.dryRun ? context.PlannedGIContributors.Count : GIContributorPaths(scene.GetRootGameObjects()).Count;
633
+ string giContributorsLine = "GI contributors: source " + sourceGIContributors.Count + " → copy " + copyGIContributors
634
+ + (options.keepSourceGI ? " (--keep-gi)" : "");
486
635
 
487
636
  if (!options.dryRun)
488
637
  {
@@ -492,6 +641,7 @@ public static class BtOptimize
492
641
  }
493
642
 
494
643
  var md = new StringBuilder("# bt-optimize tune" + (options.dryRun ? " plan (dry run — nothing changed)" : "") + " — " + scene.path + "\n\n");
644
+ md.AppendLine(giContributorsLine + "\n");
495
645
  foreach (var kind in changes.Select(change => change.Kind).Distinct())
496
646
  {
497
647
  var list = changes.Where(change => change.Kind == kind).ToList();
@@ -507,21 +657,25 @@ public static class BtOptimize
507
657
  File.WriteAllText(Path.Combine(folder, stem + ".md"), md.ToString());
508
658
  File.WriteAllText(Path.Combine(folder, stem + ".json"), ToJson(new Dictionary<string, object> {
509
659
  { "scene", scene.path },
660
+ { "giContributors", new Dictionary<string, object> { { "source", sourceGIContributors.Count }, { "copy", copyGIContributors }, { "keepSourceGI", options.keepSourceGI } } },
510
661
  { "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() },
511
662
  { "kept", kept.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "why", change.Why } }).ToList() } }, 0));
512
663
 
513
664
  var summary = new StringBuilder("tuned=" + scene.path + "\n");
514
665
  foreach (var group in changes.GroupBy(change => change.Kind)) summary.AppendLine(" " + group.Key + ": " + group.Count());
515
666
  foreach (var group in kept.GroupBy(change => change.Kind)) summary.AppendLine(" kept " + group.Key + ": " + group.Count());
667
+ summary.AppendLine(giContributorsLine);
516
668
  summary.AppendLine("needsBake=" + changes.Any(change => change.Kind != "Volume profile"));
517
669
  return summary.ToString();
518
670
  }
519
671
 
520
672
  /// <summary>
521
- /// Replaces every skinned renderer that needs no skinning with a MeshFilter + MeshRenderer on the same mesh. An
522
- /// Animator on the object is not a reason to skip it: Animators that move, scale or toggle the object (spawn pops,
523
- /// spins, bobs) keep working on a plain mesh. Only real deformation, a bone that moves on its own, a bind pose that
524
- /// differs from the mesh, or a curve / script aimed at the SkinnedMeshRenderer itself keeps a renderer skinned.
673
+ /// Replaces every skinned renderer that needs no skinning with a MeshFilter + MeshRenderer. An Animator on the object
674
+ /// is not a reason to skip it: Animators that move, scale or toggle the object (spawn pops, spins, bobs) keep working
675
+ /// on a plain mesh. One-bone props keep their mesh (or a shared offset-baked copy); a script host and a frozen pose
676
+ /// are baked as they are drawn now, copies with the same shape sharing one mesh asset; a clip that animates the
677
+ /// SkinnedMeshRenderer itself is copied with its curves aimed at MeshRenderer, on a copy of its controller. Only real
678
+ /// deformation and the still-manual cases (see SkinRigidByHand) keep a renderer skinned.
525
679
  /// </summary>
526
680
  /// <returns>How many renderers were converted (or would be, in a dry run).</returns>
527
681
  private static int UnskinRigid(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
@@ -529,44 +683,144 @@ public static class BtOptimize
529
683
  int converted = 0;
530
684
  var bakedMeshes = new Dictionary<string, Mesh>();
531
685
  string bakedFolder = UnskinnedMeshFolder(context.Scene);
686
+ string clipFolder = RetargetedClipFolder(context.Scene);
687
+ var curveAnimators = new List<Animator>();
532
688
  foreach (var renderer in context.Renderers.OfType<SkinnedMeshRenderer>().ToList())
533
689
  {
534
690
  string path = PathOf(renderer.transform);
535
691
  if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "skinned", Path = path, Why = "--exclude" }); continue; }
536
692
  var verdict = ClassifySkinning(renderer, context);
537
693
  int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
538
- string copiesNote = copies > 1 ? " — " + copies + " copies" : "";
539
- bool offsetBaked = verdict.Kind == SkinRigidOffset;
540
- if (verdict.Kind != SkinRigid && !offsetBaked)
694
+ // A baked pose is shared only by copies with the same shape, so the source mesh's copy count says nothing about it.
695
+ bool bakesShape = verdict.Kind == SkinRigidScriptHost || verdict.Kind == SkinFrozenPose;
696
+ string copiesNote = copies > 1 && !bakesShape ? " — " + copies + " copies" : "";
697
+ if (!TuneConverts(verdict.Kind))
541
698
  {
542
699
  kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
543
700
  continue;
544
701
  }
545
- // An offset bind pose is handled by moving a plain leaf object onto the mesh (the mesh stays shared by every
546
- // copy); only when that is impossible is the offset baked into a mesh asset.
547
- bool reseat = offsetBaked && CanReseatObject(renderer, context);
548
- var mesh = renderer.sharedMesh;
549
- string howPlaced = "same mesh";
550
- if (offsetBaked && !options.dryRun)
551
- {
552
- if (reseat) reseat = TryReseatObject(renderer.transform, mesh, verdict.MeshToWorld, RestPoseTolerance(renderer));
553
- if (!reseat) mesh = BakeOffsetMesh(mesh, verdict.MeshToObject, bakedFolder, bakedMeshes);
554
- }
555
- if (offsetBaked) howPlaced = reseat ? "same mesh, object moved onto the bind pose" : "baked mesh in " + bakedFolder;
556
- changes.Add(new Change { Kind = "Unskinned (rigid)", Path = path, Before = "SkinnedMeshRenderer, " + verdict.Why,
702
+ bool bakesPose = bakesShape;
703
+ string howPlaced;
704
+ var mesh = bakesPose
705
+ ? BakedPoseMesh(renderer, bakedFolder, bakedMeshes, !options.dryRun, out howPlaced)
706
+ : PlacedRigidMesh(renderer, verdict, context, options.dryRun, bakedFolder, bakedMeshes, out howPlaced);
707
+ var animators = AnimatorsWithRendererCurves(renderer);
708
+ curveAnimators.AddRange(animators);
709
+ string retargetNote = animators.Count > 0 ? "; " + RetargetPlan(animators, renderer.transform, clipFolder) : "";
710
+ bool clearsContributeGI = WithheldContributeGI(renderer.gameObject, path, context, options);
711
+ changes.Add(new Change { Kind = UnskinnedChangeKind(verdict.Kind), Path = path, Before = "SkinnedMeshRenderer, " + verdict.Why,
557
712
  After = "MeshFilter + MeshRenderer, " + howPlaced + ", same materials",
558
- Why = "skinning bought nothing: BabylonJS skins it every frame, and skinned copies can never share an instanced draw" + copiesNote });
713
+ Why = UnskinnedReason(verdict.Kind) + copiesNote + retargetNote + (clearsContributeGI ? "; Contribute GI cleared — " + KeepGIReason : "") });
559
714
  converted++;
560
- if (!options.dryRun) ReplaceWithMeshRenderer(renderer, mesh);
715
+ if (options.dryRun)
716
+ {
717
+ context.PlannedUnskinned.Add(renderer);
718
+ context.PlannedMeshKeys[renderer] = PlannedMeshKey(renderer, mesh, verdict, bakesPose, context);
719
+ continue;
720
+ }
721
+ var gameObject = renderer.gameObject;
722
+ ReplaceWithMeshRenderer(renderer, mesh);
723
+ if (clearsContributeGI) GameObjectUtility.SetStaticEditorFlags(gameObject, GameObjectUtility.GetStaticEditorFlags(gameObject) & ~StaticEditorFlags.ContributeGI);
724
+ }
725
+ if (options.dryRun)
726
+ {
727
+ RecountPlannedRepeats(context);
728
+ DiscardUnsavedMeshes(bakedMeshes.Values);
729
+ return converted;
561
730
  }
562
- if (bakedMeshes.Count > 0) AssetDatabase.SaveAssets();
731
+ RetargetAnimators(curveAnimators.Distinct().ToList(), clipFolder);
732
+ if (bakedMeshes.Count > 0 || curveAnimators.Count > 0) AssetDatabase.SaveAssets();
563
733
  return converted;
564
734
  }
565
735
 
736
+ /// <summary>
737
+ /// Which mesh a renderer a dry run plans to convert will draw: its baked pose (copies with the same shape share one
738
+ /// mesh), its own mesh (one-bone props, or an object moved onto its bind pose), or one offset-baked mesh per distinct
739
+ /// bind-pose offset. Copies only share an instanced draw when this key matches, so the dry run counts them by it.
740
+ /// </summary>
741
+ private static string PlannedMeshKey(SkinnedMeshRenderer renderer, Mesh plannedMesh, SkinningVerdict verdict, bool bakesPose, Context context)
742
+ {
743
+ if (bakesPose || !verdict.OffsetBaked || CanReseatObject(renderer, context)) return plannedMesh.GetHashCode().ToString();
744
+ return renderer.sharedMesh.GetHashCode() + "|" + OffsetKey(verdict.MeshToObject);
745
+ }
746
+
747
+ /// <summary>A dry run's repeat counts once the planned conversions draw their planned meshes (see PlannedMeshKey).</summary>
748
+ private static void RecountPlannedRepeats(Context context)
749
+ {
750
+ context.RepeatCounts.Clear();
751
+ foreach (var group in context.Renderers.GroupBy(renderer => RepeatKeyOf(renderer, context))) context.RepeatCounts[group.Key] = group.Count();
752
+ }
753
+
754
+ /// <summary>True for the skinning verdicts UnskinRigid converts to a plain mesh.</summary>
755
+ private static bool TuneConverts(string verdictKind)
756
+ {
757
+ return verdictKind == SkinRigid || verdictKind == SkinRigidOffset || verdictKind == SkinRigidScriptHost
758
+ || verdictKind == SkinRigidRendererCurves || verdictKind == SkinFrozenPose;
759
+ }
760
+
761
+ /// <summary>The tune.md change kind for a converted verdict.</summary>
762
+ private static string UnskinnedChangeKind(string verdictKind)
763
+ {
764
+ if (verdictKind == SkinRigidScriptHost) return "Unskinned (script host)";
765
+ if (verdictKind == SkinRigidRendererCurves) return "Unskinned (renderer curves)";
766
+ if (verdictKind == SkinFrozenPose) return "Unskinned (frozen pose)";
767
+ return "Unskinned (rigid)";
768
+ }
769
+
770
+ /// <summary>Why converting a renderer with this verdict is safe and what it buys.</summary>
771
+ private static string UnskinnedReason(string verdictKind)
772
+ {
773
+ const string buys = "BabylonJS skins it every frame, and skinned copies can never share an instanced draw";
774
+ 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;
775
+ if (verdictKind == SkinFrozenPose) return "its pose never changes; baked once, and copies with the same pose share the mesh asset — " + buys;
776
+ return "skinning bought nothing: " + buys;
777
+ }
778
+
779
+ /// <summary>
780
+ /// The mesh a one-bone renderer draws once converted. Its own mesh when the bind pose matches; otherwise the leaf
781
+ /// object is moved onto the bind pose (the mesh stays shared by every copy), and only when that is impossible is
782
+ /// the offset baked into a mesh asset. A dry run changes nothing and returns the skinned mesh.
783
+ /// </summary>
784
+ private static Mesh PlacedRigidMesh(SkinnedMeshRenderer renderer, SkinningVerdict verdict, Context context, bool dryRun, string bakedFolder,
785
+ Dictionary<string, Mesh> bakedMeshes, out string howPlaced)
786
+ {
787
+ var mesh = renderer.sharedMesh;
788
+ howPlaced = "same mesh";
789
+ if (!verdict.OffsetBaked) return mesh;
790
+ bool reseat = CanReseatObject(renderer, context);
791
+ if (!dryRun)
792
+ {
793
+ if (reseat) reseat = TryReseatObject(renderer.transform, mesh, verdict.MeshToWorld, RestPoseTolerance(renderer));
794
+ if (!reseat) mesh = BakeOffsetMesh(mesh, verdict.MeshToObject, bakedFolder, bakedMeshes);
795
+ }
796
+ howPlaced = reseat ? "same mesh, object moved onto the bind pose" : "baked mesh in " + bakedFolder;
797
+ return mesh;
798
+ }
799
+
800
+ /// <summary>
801
+ /// True when --keep-gi must clear Contribute GI on a converted object: it carries the flag (a SkinnedMeshRenderer
802
+ /// never takes part in the bake, the MeshRenderer that replaces it would) and did not contribute in the source.
803
+ /// Keeps the context's planned contributor set in step.
804
+ /// </summary>
805
+ private static bool WithheldContributeGI(GameObject gameObject, string path, Context context, TuneOptions options)
806
+ {
807
+ if (!GameObjectUtility.GetStaticEditorFlags(gameObject).HasFlag(StaticEditorFlags.ContributeGI)) return false;
808
+ if (WithheldFromBake(path, context, options)) return true;
809
+ context.PlannedGIContributors.Add(path);
810
+ return false;
811
+ }
812
+
813
+ /// <summary>Destroys the in-memory meshes a dry run baked to compare shapes (none of them was saved).</summary>
814
+ private static void DiscardUnsavedMeshes(IEnumerable<Mesh> meshes)
815
+ {
816
+ foreach (var mesh in meshes.Where(mesh => !EditorUtility.IsPersistent(mesh)).ToList()) UnityEngine.Object.DestroyImmediate(mesh);
817
+ }
818
+
566
819
  /// <summary>
567
820
  /// Swaps a SkinnedMeshRenderer for a MeshFilter + MeshRenderer on the same GameObject drawing `mesh` (the skinned
568
- /// mesh itself, or its offset-baked copy), with the same materials and renderer settings. Bones, colliders,
569
- /// Animators and static flags stay as they are.
821
+ /// mesh itself, its offset-baked copy or its baked pose), with the same materials and renderer settings: shadow
822
+ /// casting and receiving, occlusion, both probe usages, the probe anchor, motion vectors, rendering layers and
823
+ /// sorting. Bones, colliders, Animators and static flags stay as they are.
570
824
  /// </summary>
571
825
  private static void ReplaceWithMeshRenderer(SkinnedMeshRenderer skinned, Mesh mesh)
572
826
  {
@@ -647,7 +901,7 @@ public static class BtOptimize
647
901
  /// <summary>
648
902
  /// A light inside its own fixture (a lantern shell around the bulb) is lit fine in real time — the shadow map's near
649
903
  /// plane clips the shell — but the lightmapper traces from the bulb with no near plane, so a shadow-casting shell
650
- /// traps a baked light (Garden: lit floor under each lantern, dark walls and ceiling). The fixture's own renderers
904
+ /// traps a baked light (lit floor under each lantern, dark walls and ceiling). The fixture's own renderers
651
905
  /// whose bounds hold the light stop casting shadows.
652
906
  /// </summary>
653
907
  private static void FreeFromFixture(Light light, TuneOptions options, List<Change> changes)
@@ -694,12 +948,18 @@ public static class BtOptimize
694
948
  var lod = renderer.GetComponentInParent<LODGroup>();
695
949
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
696
950
  bool lightmappable = level <= 0 && HasUV2(renderer) && VertexAnimationOf(renderer) == null && !IsTransparent(renderer);
951
+ bool keptOutOfBake = lightmappable && WithheldFromBake(path, context, options);
952
+ bool contributesGI = lightmappable && !keptOutOfBake;
697
953
  bool keepInstanceable = IsRepeatedForInstancing(renderer, context, options);
698
954
  var newFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.ReflectionProbeStatic;
699
- if (lightmappable) newFlags |= StaticEditorFlags.ContributeGI;
955
+ if (contributesGI)
956
+ {
957
+ newFlags |= StaticEditorFlags.ContributeGI;
958
+ context.PlannedGIContributors.Add(path);
959
+ }
700
960
  var receive = renderer.receiveGI;
701
961
  // A repeated prop still contributes bounce light, but stays probe-lit so its copies share one instanced draw.
702
- bool receivesLightmaps = !keepInstanceable && (lightmappable || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)));
962
+ bool receivesLightmaps = !keepInstanceable && (contributesGI || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)));
703
963
  var newReceive = receivesLightmaps ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
704
964
  if (!options.dryRun)
705
965
  {
@@ -707,9 +967,10 @@ public static class BtOptimize
707
967
  renderer.receiveGI = newReceive;
708
968
  EditorUtility.SetDirty(renderer);
709
969
  }
710
- changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (lightmappable ? "static + ContributeGI, " : "static, ") + newReceive,
970
+ changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (contributesGI ? "static + ContributeGI, " : "static, ") + newReceive,
711
971
  Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "")
712
- + (keepInstanceable ? "; stays probe-lit — " + context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw" : "") });
972
+ + (keepInstanceable ? "; stays probe-lit — " + context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw" : "")
973
+ + (keptOutOfBake ? "; " + KeepGIReason : "") });
713
974
  }
714
975
  }
715
976
 
@@ -724,6 +985,7 @@ public static class BtOptimize
724
985
  {
725
986
  var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);
726
987
  if (!flags.HasFlag(StaticEditorFlags.BatchingStatic) && !flags.HasFlag(StaticEditorFlags.ContributeGI)) continue;
988
+ if (context.PlannedNonStatic.Contains(renderer.gameObject)) continue;
727
989
  var lod = renderer.GetComponentInParent<LODGroup>();
728
990
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
729
991
  if (level > 0) continue;
@@ -734,8 +996,11 @@ public static class BtOptimize
734
996
  string reason = NotAVisibleSurface(renderer) ?? (!HasUV2(renderer) ? "no lightmap UVs (UV2)" : VertexAnimationOf(renderer) ?? (IsTransparent(renderer) ? "transparent" : null));
735
997
  if (reason == null && IsRepeatedForInstancing(renderer, context, options))
736
998
  reason = context.RepeatCounts[RepeatKey(renderer)] + " copies: stays probe-lit so they share one instanced draw (lightmapped copies are exported as separate meshes)";
999
+ bool addsContributeGI = !flags.HasFlag(StaticEditorFlags.ContributeGI);
1000
+ if (reason == null && addsContributeGI && WithheldFromBake(path, context, options)) reason = KeepGIReason;
737
1001
  if (reason != null) { kept.Add(new Change { Kind = "probe-lit", Path = path, Why = reason }); continue; }
738
- string before = (flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI, " : "no ContributeGI, ") + renderer.receiveGI;
1002
+ string before = (addsContributeGI ? "no ContributeGI, " : "ContributeGI, ") + renderer.receiveGI;
1003
+ context.PlannedGIContributors.Add(path);
739
1004
  if (!options.dryRun)
740
1005
  {
741
1006
  GameObjectUtility.SetStaticEditorFlags(renderer.gameObject, flags | StaticEditorFlags.ContributeGI);
@@ -751,8 +1016,15 @@ public static class BtOptimize
751
1016
  {
752
1017
  if (!HasUV2(lower)) continue;
753
1018
  lowerLevels++;
1019
+ // --keep-gi keeps a lower level's own Contribute GI too: the copy's contributor set stays the source's.
1020
+ var lowerFlags = GameObjectUtility.GetStaticEditorFlags(lower.gameObject) | StaticEditorFlags.BatchingStatic;
1021
+ if (!options.keepSourceGI)
1022
+ {
1023
+ lowerFlags &= ~StaticEditorFlags.ContributeGI;
1024
+ context.PlannedGIContributors.Remove(PathOf(lower.transform));
1025
+ }
754
1026
  if (options.dryRun) continue;
755
- GameObjectUtility.SetStaticEditorFlags(lower.gameObject, GameObjectUtility.GetStaticEditorFlags(lower.gameObject) & ~StaticEditorFlags.ContributeGI | StaticEditorFlags.BatchingStatic);
1027
+ GameObjectUtility.SetStaticEditorFlags(lower.gameObject, lowerFlags);
756
1028
  lower.receiveGI = ReceiveGI.Lightmaps;
757
1029
  EditorUtility.SetDirty(lower);
758
1030
  }
@@ -762,6 +1034,348 @@ public static class BtOptimize
762
1034
  }
763
1035
  }
764
1036
 
1037
+ /// <summary>
1038
+ /// Every unlightmapped copy in a repeat group (instanceRepeatsFrom copies or more of one mesh + materials) gets
1039
+ /// Light Probe Usage Off and Receive GI Light Probes, so its copies share one instanced draw: the toolkit loads every
1040
+ /// node that carries light probe data as its own mesh (SceneManager.DeinstanceProbeLitNodes). Reflection Probe Usage
1041
+ /// and Contribute GI stay as they are. Runs last of the renderer steps, so it sees what Lightmap probe-lit left
1042
+ /// unlightmapped; in a dry run it also covers the skinned copies UnskinRigid plans to convert.
1043
+ /// </summary>
1044
+ private static void InstanceRepeats(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
1045
+ {
1046
+ var candidates = context.Renderers.OfType<MeshRenderer>().Cast<Renderer>().Concat(context.PlannedUnskinned);
1047
+ foreach (var renderer in candidates)
1048
+ {
1049
+ if (!IsRepeatedForInstancing(renderer, context, options)) continue;
1050
+ string path = PathOf(renderer.transform);
1051
+ if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "probe-lit repeat", Path = path, Why = "--exclude" }); continue; }
1052
+ var meshRenderer = renderer as MeshRenderer;
1053
+ // A converted skinned renderer comes out Receive GI Light Probes (see ReplaceWithMeshRenderer).
1054
+ var receive = meshRenderer != null ? meshRenderer.receiveGI : ReceiveGI.LightProbes;
1055
+ bool lightmapped = receive == ReceiveGI.Lightmaps && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI);
1056
+ if (lightmapped) continue;
1057
+ if (renderer.lightProbeUsage == LightProbeUsage.Off && receive == ReceiveGI.LightProbes) continue;
1058
+ changes.Add(new Change { Kind = "Light probes off (instancing)", Path = path,
1059
+ Before = "Light Probes " + renderer.lightProbeUsage + ", Receive GI " + receive + (meshRenderer == null ? " (once unskinned)" : ""),
1060
+ After = "Light Probes Off, Receive GI LightProbes, Reflection Probes " + renderer.reflectionProbeUsage,
1061
+ Why = context.RepeatCounts[RepeatKeyOf(renderer, context)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
1062
+ + " (SceneManager.DeinstanceProbeLitNodes); the copies light from the scene's ambient instead of the nearest probe" });
1063
+ if (options.dryRun || meshRenderer == null) continue;
1064
+ meshRenderer.lightProbeUsage = LightProbeUsage.Off;
1065
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
1066
+ EditorUtility.SetDirty(meshRenderer);
1067
+ }
1068
+ }
1069
+
1070
+ /// <summary>
1071
+ /// Clears every static flag on an object that is marked static but moves in the browser: a clip or Timeline moves it
1072
+ /// or an ancestor, or a physics body or navigation agent does (see BrowserMoverOf). The exporter freezes a static
1073
+ /// object's world matrix, so a static spinning, bobbing or popping prop would stand still; and a lightmap baked in one
1074
+ /// place is wrong once the object moves, so its renderer becomes probe-lit. Runs before the static and lightmap
1075
+ /// steps, which then leave these objects alone.
1076
+ /// </summary>
1077
+ private static void UnfreezeAnimated(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
1078
+ {
1079
+ foreach (var transform in context.Roots.SelectMany(root => root.GetComponentsInChildren<Transform>(true)))
1080
+ {
1081
+ var gameObject = transform.gameObject;
1082
+ var flags = GameObjectUtility.GetStaticEditorFlags(gameObject);
1083
+ if (flags == 0) continue;
1084
+ string mover = BrowserMoverOf(transform, context);
1085
+ if (mover == null) continue;
1086
+ string path = PathOf(transform);
1087
+ if (IsExcluded(transform, options.exclude)) { kept.Add(new Change { Kind = "static, but moves", Path = path, Why = "--exclude; " + mover }); continue; }
1088
+ var meshRenderer = gameObject.GetComponent<MeshRenderer>();
1089
+ bool wasLightmapped = meshRenderer != null && meshRenderer.receiveGI == ReceiveGI.Lightmaps;
1090
+ context.PlannedNonStatic.Add(gameObject);
1091
+ context.PlannedGIContributors.Remove(path);
1092
+ changes.Add(new Change { Kind = "Static cleared (moves in the browser)", Path = path, Before = "static (" + flags + ")" + (wasLightmapped ? ", Lightmaps" : ""),
1093
+ After = "not static" + (meshRenderer != null ? ", LightProbes" : ""),
1094
+ Why = mover + ": the exporter freezes a static object's world matrix, so it would stand still in the browser"
1095
+ + (wasLightmapped ? "; a lightmap baked in one place is wrong once it moves" : "") });
1096
+ if (options.dryRun) continue;
1097
+ GameObjectUtility.SetStaticEditorFlags(gameObject, 0);
1098
+ if (meshRenderer != null)
1099
+ {
1100
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
1101
+ EditorUtility.SetDirty(meshRenderer);
1102
+ }
1103
+ EditorUtility.SetDirty(gameObject);
1104
+ }
1105
+ }
1106
+
1107
+ /// <summary>
1108
+ /// What moves the object in the browser — a clip or Timeline on it or an ancestor (Context.AnimatedTransforms), or a
1109
+ /// Rigidbody, CharacterController or NavMeshAgent on it or an ancestor — or null. Narrower than WebDriverOf on
1110
+ /// purpose: an Animator on a level root that only animates one light does not move the rest of the level.
1111
+ /// </summary>
1112
+ private static string BrowserMoverOf(Transform transform, Context context)
1113
+ {
1114
+ for (var node = transform; node != null; node = node.parent)
1115
+ {
1116
+ string where = node == transform ? "" : "'" + node.name + "' above it: ";
1117
+ if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return where + "moved by " + animator;
1118
+ foreach (var component in node.GetComponents<Component>())
1119
+ if (component is Rigidbody || component is CharacterController || component is UnityEngine.AI.NavMeshAgent)
1120
+ return where + "moved by its " + component.GetType().Name;
1121
+ }
1122
+ return null;
1123
+ }
1124
+
1125
+ /// <summary>The toolkit component that switches a rig to vertex animation textures (CanvasTools.dll).</summary>
1126
+ private const string AnimatorControlRigTypeName = "AnimatorControlRig";
1127
+
1128
+ /// <summary>The AnimatorControlRig.animationMode value that exports baked vertex animation textures.</summary>
1129
+ private const string VertexAnimationModeName = "UseVertexAnimations";
1130
+
1131
+ /// <summary>The toolkit shader a vertex-animated renderer's materials must use (AnimatorControlRigEditor.VAT_SHADER_NAME).</summary>
1132
+ private const string VertexAnimationShaderName = "Babylon/Custom/Vertex Animation Shader";
1133
+
1134
+ /// <summary>Colour properties a VAT material copy takes its tint from, in order of preference (URP / HDRP, then Built-in).</summary>
1135
+ private static readonly string[] VatColorSources = { "_BaseColor", "_Color" };
1136
+
1137
+ /// <summary>Texture properties copied onto a VAT material: source names in order of preference, and the VAT shader's name.</summary>
1138
+ private static readonly (string[] Sources, string Target)[] VatTextureProperties = {
1139
+ (new[] { "_BaseMap", "_BaseColorMap", "_MainTex" }, "_MainTex"), (new[] { "_BumpMap", "_NormalMap" }, "_BumpMap") };
1140
+
1141
+ /// <summary>Float properties copied onto a VAT material: source names in order of preference, and the VAT shader's name.</summary>
1142
+ private static readonly (string[] Sources, string Target)[] VatFloatProperties = {
1143
+ (new[] { "_Smoothness", "_Glossiness" }, "_Glossiness"), (new[] { "_Metallic" }, "_Metallic"), (new[] { "_BumpScale", "_NormalScale" }, "_BumpScale") };
1144
+
1145
+ /// <summary>World scale counts as 1 within this tolerance.</summary>
1146
+ private const float UnitScaleTolerance = 0.0001f;
1147
+
1148
+ /// <summary>One animated character: an Animator and the skinned renderers it drives (not those under a nested Animator).</summary>
1149
+ private sealed class Character
1150
+ {
1151
+ public readonly Animator Animator;
1152
+ public readonly SkinnedMeshRenderer[] Renderers;
1153
+ /// <summary>The meshes the character draws, as one key: characters with equal keys are copies of one character.</summary>
1154
+ public readonly string MeshKey;
1155
+
1156
+ public Character(Animator animator, SkinnedMeshRenderer[] renderers)
1157
+ {
1158
+ Animator = animator;
1159
+ Renderers = renderers;
1160
+ MeshKey = string.Join(",", renderers.Select(renderer => renderer.sharedMesh != null ? renderer.sharedMesh.GetHashCode() : 0).OrderBy(hash => hash));
1161
+ }
1162
+ }
1163
+
1164
+ /// <summary>
1165
+ /// Makes every crowd of a really deforming character (vatCrowdsFrom copies or more: Animators whose skinned renderers
1166
+ /// draw the same meshes) a vertex-animation crowd. Skinned copies can never share an instanced draw, and each is
1167
+ /// skinned every frame; with the toolkit's AnimatorControlRig in UseVertexAnimations mode the exporter bakes each
1168
+ /// controller's clips to vertex animation textures and the browser draws the copies as instances — one draw per
1169
+ /// material in view — each keeping its own Animator state. Its materials are copied onto the toolkit's
1170
+ /// vertex-animation shader (one copy per source material, shared by every copy), its renderers get world scale 1
1171
+ /// (the baker writes world-size positions and the browser applies the renderer node's scale again; Unity draws a
1172
+ /// skinned mesh from its bones, so it looks the same) and Light Probes Off (the toolkit de-instances probe-lit nodes).
1173
+ /// Runs after the renderer steps; characters with blend shapes, cloth, transparent materials or a renderer that is
1174
+ /// also a bone or parent are reported, not converted.
1175
+ /// </summary>
1176
+ private static void VatCrowds(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
1177
+ {
1178
+ var drawn = new HashSet<Renderer>(context.Renderers);
1179
+ var plannedUnskinned = new HashSet<SkinnedMeshRenderer>(context.PlannedUnskinned);
1180
+ var characters = context.All<Animator>()
1181
+ .Where(animator => animator.isActiveAndEnabled && animator.runtimeAnimatorController != null)
1182
+ .Select(animator => new Character(animator, animator.GetComponentsInChildren<SkinnedMeshRenderer>(true)
1183
+ .Where(skinned => drawn.Contains(skinned) && !plannedUnskinned.Contains(skinned) && skinned.GetComponentInParent<Animator>() == animator)
1184
+ .ToArray()))
1185
+ .Where(character => character.Renderers.Length > 0)
1186
+ .ToList();
1187
+ var rigType = AnimatorControlRigType();
1188
+ var vatShader = Shader.Find(VertexAnimationShaderName);
1189
+ string folder = VatCrowdFolder(context.Scene);
1190
+ var vatMaterials = new Dictionary<Material, Material>();
1191
+ foreach (var crowd in characters.GroupBy(character => character.MeshKey).Where(group => group.Count() >= options.vatCrowdsFrom))
1192
+ {
1193
+ var members = new List<Character>();
1194
+ foreach (var character in crowd)
1195
+ {
1196
+ if (IsExcluded(character.Animator.transform, options.exclude)) kept.Add(new Change { Kind = "deforming crowd", Path = PathOf(character.Animator.transform), Why = "--exclude" });
1197
+ else if (!IsVertexAnimated(character.Animator, rigType)) members.Add(character);
1198
+ }
1199
+ if (members.Count == 0) continue;
1200
+ string blocker = rigType == null ? "this toolkit build has no " + AnimatorControlRigTypeName + " (update CanvasTools.dll)"
1201
+ : vatShader == null ? "shader '" + VertexAnimationShaderName + "' not found (update the toolkit editor package)"
1202
+ : members.Select(VatBlocker).FirstOrDefault(reason => reason != null);
1203
+ string copies = crowd.Count() + " copies of one deforming character";
1204
+ if (blocker != null)
1205
+ {
1206
+ foreach (var member in members) kept.Add(new Change { Kind = "deforming crowd", Path = PathOf(member.Animator.transform), Why = copies + "; not made a VAT crowd: " + blocker });
1207
+ continue;
1208
+ }
1209
+ foreach (var member in members)
1210
+ {
1211
+ changes.Add(new Change { Kind = "VAT crowd", Path = PathOf(member.Animator.transform),
1212
+ Before = member.Renderers.Length + " SkinnedMeshRenderer (skinned every frame, one draw per copy per pass)",
1213
+ After = AnimatorControlRigTypeName + " " + VertexAnimationModeName + ", VAT materials in " + folder + ", renderer world scale 1, Light Probes Off",
1214
+ Why = copies + " (controller " + member.Animator.runtimeAnimatorController.name + "): skinned copies never instance; baked to vertex animation"
1215
+ + " textures they draw instanced, one draw per material in view, each keeping its own Animator state. The Editor draws the VAT shader"
1216
+ + " magenta in URP / HDRP: judge the crowd in the browser" });
1217
+ if (options.dryRun) continue;
1218
+ ConfigureVertexAnimationRig(member.Animator, rigType, member.Renderers);
1219
+ foreach (var skinned in member.Renderers)
1220
+ {
1221
+ skinned.sharedMaterials = skinned.sharedMaterials.Select(material => VatMaterial(material, vatShader, folder, vatMaterials)).ToArray();
1222
+ SetUnitWorldScale(skinned.transform);
1223
+ skinned.lightProbeUsage = LightProbeUsage.Off;
1224
+ EditorUtility.SetDirty(skinned);
1225
+ }
1226
+ }
1227
+ }
1228
+ if (!options.dryRun && vatMaterials.Count > 0) AssetDatabase.SaveAssets();
1229
+ }
1230
+
1231
+ /// <summary>Why a character cannot become a VAT crowd member automatically, or null.</summary>
1232
+ private static string VatBlocker(Character character)
1233
+ {
1234
+ foreach (var skinned in character.Renderers)
1235
+ {
1236
+ string name = "'" + skinned.name + "'";
1237
+ if (skinned.sharedMesh == null) return name + " has no mesh";
1238
+ if (skinned.sharedMesh.blendShapeCount > 0) return name + " has blend shapes (vertex animation textures bake bones only)";
1239
+ if (skinned.GetComponent<Cloth>() != null) return name + " has Cloth";
1240
+ if (IsTransparent(skinned)) return name + " is transparent (the VAT shader is opaque)";
1241
+ if (skinned.transform.childCount > 0 || character.Renderers.Any(other => other.bones.Contains(skinned.transform)))
1242
+ return name + " is also a bone or a parent: setting its world scale to 1 would move what hangs under it — set up the AnimatorControlRig by hand";
1243
+ var parentScale = skinned.transform.parent != null ? skinned.transform.parent.lossyScale : Vector3.one;
1244
+ if (Mathf.Abs(parentScale.x - parentScale.y) > UnitScaleTolerance * parentScale.x || Mathf.Abs(parentScale.x - parentScale.z) > UnitScaleTolerance * parentScale.x)
1245
+ return name + " sits under a non-uniform scale: its world scale cannot be set to 1 — set up the AnimatorControlRig by hand";
1246
+ if (skinned.sharedMaterials.Any(material => material != null && material.shader.name != VertexAnimationShaderName && !VatTextureProperties[0].Sources.Any(material.HasProperty)))
1247
+ return name + " uses a material with no base colour texture property Tune knows (" + string.Join(", ", VatTextureProperties[0].Sources) + ")";
1248
+ }
1249
+ return null;
1250
+ }
1251
+
1252
+ /// <summary>The toolkit's AnimatorControlRig type, found by name in the loaded assemblies, or null when this toolkit build has none.</summary>
1253
+ private static Type AnimatorControlRigType()
1254
+ {
1255
+ return AppDomain.CurrentDomain.GetAssemblies()
1256
+ .Select(assembly => assembly.GetType(AnimatorControlRigTypeName, false))
1257
+ .FirstOrDefault(type => type != null && type.GetField("animationMode") != null && type.GetField("meshRenderers") != null);
1258
+ }
1259
+
1260
+ /// <summary>True when the animator already has an AnimatorControlRig in vertex-animation mode.</summary>
1261
+ private static bool IsVertexAnimated(Animator animator, Type rigType)
1262
+ {
1263
+ var rig = rigType != null ? animator.GetComponent(rigType) : null;
1264
+ return rig != null && rigType.GetField("animationMode").GetValue(rig).ToString() == VertexAnimationModeName;
1265
+ }
1266
+
1267
+ /// <summary>Adds (or reuses) the animator's AnimatorControlRig and sets it to vertex animations over the renderers.</summary>
1268
+ private static void ConfigureVertexAnimationRig(Animator animator, Type rigType, SkinnedMeshRenderer[] skinnedRenderers)
1269
+ {
1270
+ var rig = animator.GetComponent(rigType);
1271
+ if (rig == null) rig = animator.gameObject.AddComponent(rigType);
1272
+ var modeField = rigType.GetField("animationMode");
1273
+ modeField.SetValue(rig, Enum.Parse(modeField.FieldType, VertexAnimationModeName));
1274
+ rigType.GetField("meshRenderers").SetValue(rig, skinnedRenderers);
1275
+ EditorUtility.SetDirty(rig);
1276
+ }
1277
+
1278
+ /// <summary>
1279
+ /// The vertex-animation copy of a material (tint, base colour and normal maps with their tiling, smoothness, metallic,
1280
+ /// normal strength), saved in the folder as &lt;material&gt;_VAT.mat and updated in place on a re-run so its GUID stays
1281
+ /// stable. Every copy of the character shares it. A material already on the vertex-animation shader is returned as it is.
1282
+ /// </summary>
1283
+ private static Material VatMaterial(Material source, Shader vatShader, string folder, Dictionary<Material, Material> vatMaterials)
1284
+ {
1285
+ if (source == null || source.shader == vatShader) return source;
1286
+ if (vatMaterials.TryGetValue(source, out var existing)) return existing;
1287
+ var vat = new Material(vatShader) { name = source.name + "_VAT", enableInstancing = true };
1288
+ string colorSource = VatColorSources.FirstOrDefault(source.HasProperty);
1289
+ if (colorSource != null && vat.HasProperty("_Color")) vat.SetColor("_Color", source.GetColor(colorSource));
1290
+ foreach (var (sources, target) in VatTextureProperties)
1291
+ {
1292
+ string from = sources.FirstOrDefault(source.HasProperty);
1293
+ if (from == null || !vat.HasProperty(target)) continue;
1294
+ vat.SetTexture(target, source.GetTexture(from));
1295
+ vat.SetTextureScale(target, source.GetTextureScale(from));
1296
+ vat.SetTextureOffset(target, source.GetTextureOffset(from));
1297
+ }
1298
+ foreach (var (sources, target) in VatFloatProperties)
1299
+ {
1300
+ string from = sources.FirstOrDefault(source.HasProperty);
1301
+ if (from != null && vat.HasProperty(target)) vat.SetFloat(target, source.GetFloat(from));
1302
+ }
1303
+ if (vat.HasProperty("_BumpMap") && vat.GetTexture("_BumpMap") != null) vat.EnableKeyword("_NORMALMAP");
1304
+ EnsureFolder(folder);
1305
+ string assetPath = folder + "/" + vat.name + ".mat";
1306
+ var previous = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
1307
+ if (previous == null) AssetDatabase.CreateAsset(vat, assetPath);
1308
+ else
1309
+ {
1310
+ EditorUtility.CopySerialized(vat, previous);
1311
+ UnityEngine.Object.DestroyImmediate(vat);
1312
+ vat = previous;
1313
+ }
1314
+ vatMaterials[source] = vat;
1315
+ return vat;
1316
+ }
1317
+
1318
+ /// <summary>Sets the object's local scale so its world scale is 1 (its parents are scaled uniformly; see VatBlocker).</summary>
1319
+ private static void SetUnitWorldScale(Transform transform)
1320
+ {
1321
+ float parentScale = transform.parent != null ? transform.parent.lossyScale.x : 1f;
1322
+ transform.localScale = Vector3.one / parentScale;
1323
+ }
1324
+
1325
+ /// <summary>True when the object's world scale is 1 on every axis, within UnitScaleTolerance.</summary>
1326
+ private static bool HasUnitWorldScale(Transform transform)
1327
+ {
1328
+ var scale = transform.lossyScale;
1329
+ return Mathf.Abs(scale.x - 1f) < UnitScaleTolerance && Mathf.Abs(scale.y - 1f) < UnitScaleTolerance && Mathf.Abs(scale.z - 1f) < UnitScaleTolerance;
1330
+ }
1331
+
1332
+ /// <summary>Folder for the VAT material copies: &lt;scene folder&gt;/&lt;scene&gt;_VatCrowd (BtCombine.PrepareCopy reset and RemoveCopy delete it).</summary>
1333
+ private static string VatCrowdFolder(Scene scene)
1334
+ {
1335
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_VatCrowd";
1336
+ }
1337
+
1338
+ /// <summary>
1339
+ /// True when --keep-gi forbids Contribute GI on the object at this hierarchy path: it did not contribute GI in the
1340
+ /// source scene, and adding it would pull the object into the re-bake (darkening the source's indirect light).
1341
+ /// </summary>
1342
+ private static bool WithheldFromBake(string path, Context context, TuneOptions options)
1343
+ {
1344
+ return options.keepSourceGI && !context.SourceGIContributors.Contains(path);
1345
+ }
1346
+
1347
+ /// <summary>
1348
+ /// The hierarchy paths of the renderers that contribute GI in this scene's source: the scene named in the report
1349
+ /// folder's working-copy.txt, opened additively and closed again unsaved (an already open source is only read). A
1350
+ /// scene without that record (a dry run on the source itself) is its own source.
1351
+ /// </summary>
1352
+ private static HashSet<string> SourceGIContributorsOf(Scene scene, string reportFolder)
1353
+ {
1354
+ string recordPath = Path.Combine(reportFolder, "working-copy.txt");
1355
+ string sourcePath = File.Exists(recordPath) ? File.ReadAllText(recordPath).Trim() : scene.path;
1356
+ if (sourcePath == scene.path) return GIContributorPaths(scene.GetRootGameObjects());
1357
+ var openSource = SceneManager.GetSceneByPath(sourcePath);
1358
+ if (openSource.isLoaded) return GIContributorPaths(openSource.GetRootGameObjects());
1359
+ var source = EditorSceneManager.OpenScene(sourcePath, OpenSceneMode.Additive);
1360
+ try
1361
+ {
1362
+ return GIContributorPaths(source.GetRootGameObjects());
1363
+ }
1364
+ finally
1365
+ {
1366
+ EditorSceneManager.CloseScene(source, true);
1367
+ }
1368
+ }
1369
+
1370
+ /// <summary>The hierarchy paths of the active, enabled MeshRenderers under the roots whose objects have Contribute GI.</summary>
1371
+ private static HashSet<string> GIContributorPaths(IEnumerable<GameObject> roots)
1372
+ {
1373
+ return new HashSet<string>(roots.SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(true))
1374
+ .Where(renderer => renderer.enabled && renderer.gameObject.activeInHierarchy)
1375
+ .Where(renderer => GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI))
1376
+ .Select(renderer => PathOf(renderer.transform)));
1377
+ }
1378
+
765
1379
  /// <summary>
766
1380
  /// A motion blur override with intensity 0 does nothing in Unity (MotionBlur.IsActive() is false), but older
767
1381
  /// toolkit runtimes still build a motion blur post-process and the buffers it needs. Deactivating the override
@@ -792,11 +1406,309 @@ public static class BtOptimize
792
1406
  }
793
1407
  }
794
1408
 
1409
+ // ------------------------------------------------------------------------------------------------------------
1410
+ // Shadow casters — pruned per object, from the browser's per-cascade caster dump, proven by capture
1411
+ // ------------------------------------------------------------------------------------------------------------
1412
+
1413
+ /// <summary>The file PruneShadowCasters keeps in the working copy's report folder: what it pruned and each renderer's original mode.</summary>
1414
+ private const string PrunedCastersFileName = "pruned-casters.json";
1415
+
1416
+ /// <summary>Settings for PruneShadowCasters.</summary>
1417
+ [Serializable]
1418
+ public class CasterOptions
1419
+ {
1420
+ /// <summary>
1421
+ /// The complete prune list: renderers (object names or hierarchy paths) that stop casting shadows. A renderer an
1422
+ /// earlier run pruned that this list no longer names gets its original Cast Shadows mode back.
1423
+ /// </summary>
1424
+ public string[] paths = new string[0];
1425
+ /// <summary>Report what would change without changing it.</summary>
1426
+ public bool dryRun = false;
1427
+ }
1428
+
1429
+ /// <summary>What PruneShadowCasters last pruned: hierarchy paths and, at the same index, each one's original Cast Shadows mode.</summary>
1430
+ [Serializable]
1431
+ private class PrunedCasterRecord
1432
+ {
1433
+ public string[] paths = new string[0];
1434
+ public string[] modes = new string[0];
1435
+ }
1436
+
1437
+ /// <summary>
1438
+ /// Sets Cast Shadows Off on every renderer in the prune list (Receive Shadows stays as it is) and gives every renderer
1439
+ /// an earlier run pruned that the list no longer names its original mode back, so the list can be edited and re-run
1440
+ /// at any time. The list comes from the browser's per-cascade caster dump (`profile-browser.mjs --casters true`) and
1441
+ /// survey.md's flat-surface candidates, and each entry stays only if the Unity captures at the pinned poses show no
1442
+ /// visible shadow change. Cast Shadows also drives the lightmapper's occlusion, so bake after pruning. Works only on a
1443
+ /// bt-optimize working copy; saves the scene and writes pruned-casters.json.
1444
+ /// </summary>
1445
+ /// <param name="optionsJson">A CasterOptions object as JSON, e.g. {"paths":["Level/Road","Ground*"]}.</param>
1446
+ /// <returns>A summary: renderers pruned, renderers restored, names that matched nothing.</returns>
1447
+ public static string PruneShadowCasters(string optionsJson)
1448
+ {
1449
+ var options = string.IsNullOrWhiteSpace(optionsJson) ? new CasterOptions() : JsonUtility.FromJson<CasterOptions>(optionsJson);
1450
+ var scene = SceneManager.GetActiveScene();
1451
+ string folder = ReportFolder(scene);
1452
+ if (!File.Exists(Path.Combine(folder, "working-copy.txt")))
1453
+ throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; PruneShadowCasters never edits a source scene.");
1454
+ var renderers = new Context(scene).Renderers;
1455
+ string recordPath = Path.Combine(folder, PrunedCastersFileName);
1456
+ var previous = ReadPrunedCasters(recordPath);
1457
+ var originalModes = new Dictionary<string, string>();
1458
+ for (int i = 0; i < previous.paths.Length && i < previous.modes.Length; i++) originalModes[previous.paths[i]] = previous.modes[i];
1459
+
1460
+ var pruned = new Dictionary<string, string>();
1461
+ var unmatched = new List<string>();
1462
+ int changed = 0;
1463
+ foreach (string nameOrPath in options.paths)
1464
+ {
1465
+ var matches = renderers.Where(renderer => MatchesName(renderer.name, new[] { nameOrPath }) || PathOf(renderer.transform) == nameOrPath).ToList();
1466
+ if (matches.Count == 0) { unmatched.Add(nameOrPath); continue; }
1467
+ foreach (var renderer in matches)
1468
+ {
1469
+ string path = PathOf(renderer.transform);
1470
+ pruned[path] = originalModes.TryGetValue(path, out var original) ? original : renderer.shadowCastingMode.ToString();
1471
+ if (renderer.shadowCastingMode == ShadowCastingMode.Off) continue;
1472
+ changed++;
1473
+ if (options.dryRun) continue;
1474
+ renderer.shadowCastingMode = ShadowCastingMode.Off;
1475
+ EditorUtility.SetDirty(renderer);
1476
+ }
1477
+ }
1478
+ int restored = 0;
1479
+ foreach (var entry in originalModes.Where(entry => !pruned.ContainsKey(entry.Key)))
1480
+ foreach (var renderer in renderers.Where(renderer => PathOf(renderer.transform) == entry.Key && renderer.shadowCastingMode == ShadowCastingMode.Off))
1481
+ {
1482
+ restored++;
1483
+ if (options.dryRun) continue;
1484
+ renderer.shadowCastingMode = (ShadowCastingMode)Enum.Parse(typeof(ShadowCastingMode), entry.Value);
1485
+ EditorUtility.SetDirty(renderer);
1486
+ }
1487
+ if (!options.dryRun)
1488
+ {
1489
+ File.WriteAllText(recordPath, JsonUtility.ToJson(new PrunedCasterRecord { paths = pruned.Keys.ToArray(), modes = pruned.Values.ToArray() }, true));
1490
+ EditorSceneManager.MarkSceneDirty(scene);
1491
+ EditorSceneManager.SaveScene(scene);
1492
+ }
1493
+ return (options.dryRun ? "dry run — nothing changed\n" : "") + "pruned=" + pruned.Count + " (newly off " + changed + ") restored=" + restored
1494
+ + "\nunmatched=" + string.Join(", ", unmatched) + "\nneedsBake=" + (changed + restored > 0);
1495
+ }
1496
+
1497
+ /// <summary>
1498
+ /// Reads the prune record. A plain JSON array of paths (written by a hand-made prune step before this one existed) is
1499
+ /// read as renderers that cast On in the source.
1500
+ /// </summary>
1501
+ private static PrunedCasterRecord ReadPrunedCasters(string recordPath)
1502
+ {
1503
+ if (!File.Exists(recordPath)) return new PrunedCasterRecord();
1504
+ string text = File.ReadAllText(recordPath).Trim();
1505
+ if (!text.StartsWith("[", StringComparison.Ordinal)) return JsonUtility.FromJson<PrunedCasterRecord>(text);
1506
+ var paths = System.Text.RegularExpressions.Regex.Matches(text, "\"((?:[^\"\\\\]|\\\\.)*)\"")
1507
+ .Cast<System.Text.RegularExpressions.Match>().Select(match => System.Text.RegularExpressions.Regex.Unescape(match.Groups[1].Value)).ToArray();
1508
+ return new PrunedCasterRecord { paths = paths, modes = paths.Select(path => ShadowCastingMode.On.ToString()).ToArray() };
1509
+ }
1510
+
1511
+ // ------------------------------------------------------------------------------------------------------------
1512
+ // Verify — the working copy against its source and the Tune rules
1513
+ // ------------------------------------------------------------------------------------------------------------
1514
+
1515
+ /// <summary>
1516
+ /// Checks the active working copy against its source (the scene named in working-copy.txt) and the Tune rules, and
1517
+ /// writes verify.md / verify.json. Problems: unsaved changes; a pose camera left in the scene; a camera whose enabled
1518
+ /// state differs from the source (a capture step that disabled the main camera and was saved ships a game with no
1519
+ /// post-processing); lighting settings that differ from the source; rigid skinned meshes Tune converts that are
1520
+ /// still skinned; repeated meshes (instanceRepeatsFrom copies or more) that are lightmapped or probe-lit; static
1521
+ /// objects that move in the browser; VAT crowd members missing their materials, unit scale or probes-off; pruned
1522
+ /// shadow casters casting again; with keepSourceGI, GI contributors the source does not have. Changes nothing.
1523
+ /// </summary>
1524
+ /// <param name="optionsJson">The TuneOptions the copy was tuned with (thresholds and exclusions), or empty for the defaults.</param>
1525
+ /// <returns>"problems=N" and one line per problem.</returns>
1526
+ public static string Verify(string optionsJson)
1527
+ {
1528
+ var options = string.IsNullOrWhiteSpace(optionsJson) ? new TuneOptions() : JsonUtility.FromJson<TuneOptions>(optionsJson);
1529
+ var scene = SceneManager.GetActiveScene();
1530
+ string folder = ReportFolder(scene);
1531
+ string recordPath = Path.Combine(folder, "working-copy.txt");
1532
+ if (!File.Exists(recordPath)) throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy (no " + recordPath + ").");
1533
+ string sourcePath = File.ReadAllText(recordPath).Trim();
1534
+ var context = new Context(scene);
1535
+ var problems = new List<string>();
1536
+ var checks = new Dictionary<string, object>();
1537
+
1538
+ if (scene.isDirty) problems.Add("the scene has unsaved changes — save it before exporting");
1539
+ if (scene.GetRootGameObjects().Any(root => root.name == PoseCameraName)) problems.Add(PoseCameraName + " is in the scene — reopen the scene before exporting (it would export as a camera)");
1540
+
1541
+ var copyCameras = CameraStates(scene);
1542
+ var copyLighting = ReadLighting(scene);
1543
+ var source = ReadFromScene(sourcePath, scene, sourceScene => new { cameras = CameraStates(sourceScene), lighting = ReadLighting(sourceScene), contributors = GIContributorPaths(sourceScene.GetRootGameObjects()) });
1544
+ foreach (var camera in source.cameras)
1545
+ {
1546
+ if (!copyCameras.TryGetValue(camera.Key, out bool enabled)) problems.Add("camera " + camera.Key + " is missing from the copy");
1547
+ else if (enabled != camera.Value) problems.Add("camera " + camera.Key + " is " + (enabled ? "enabled" : "disabled") + " in the copy but " + (camera.Value ? "enabled" : "disabled") + " in the source");
1548
+ }
1549
+ foreach (var setting in source.lighting.Where(setting => !copyLighting.TryGetValue(setting.Key, out var value) || value != setting.Value))
1550
+ problems.Add("lighting " + setting.Key + ": copy " + (copyLighting.TryGetValue(setting.Key, out var copyValue) ? copyValue : "missing") + ", source " + setting.Value);
1551
+ checks["lighting"] = copyLighting.ToDictionary(pair => pair.Key, pair => (object)pair.Value);
1552
+
1553
+ var rigidLeft = context.Renderers.OfType<SkinnedMeshRenderer>().Where(renderer => !IsExcluded(renderer.transform, options.exclude))
1554
+ .Where(renderer => options.unskinRigid && TuneConverts(ClassifySkinning(renderer, context).Kind)).Select(renderer => PathOf(renderer.transform)).ToList();
1555
+ problems.AddRange(rigidLeft.Select(path => "still skinned although it needs no skinning: " + path));
1556
+ checks["rigidSkinnedLeft"] = rigidLeft.Count;
1557
+ checks["skinnedLeft"] = context.Renderers.OfType<SkinnedMeshRenderer>().Count();
1558
+
1559
+ var repeats = options.instanceRepeatsFrom <= 0 ? new List<Renderer>() : context.Renderers.OfType<MeshRenderer>().Cast<Renderer>()
1560
+ .Where(renderer => !IsExcluded(renderer.transform, options.exclude) && IsRepeatedForInstancing(renderer, context, options)).ToList();
1561
+ var lightmappedRepeats = repeats.Where(renderer => ((MeshRenderer)renderer).receiveGI == ReceiveGI.Lightmaps
1562
+ && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI)).Select(renderer => PathOf(renderer.transform)).ToList();
1563
+ var probeLitRepeats = repeats.Where(renderer => renderer.lightProbeUsage != LightProbeUsage.Off).Select(renderer => PathOf(renderer.transform)).Except(lightmappedRepeats).ToList();
1564
+ problems.AddRange(lightmappedRepeats.Select(path => "repeated mesh is lightmapped (its copies cannot instance): " + path));
1565
+ problems.AddRange(probeLitRepeats.Select(path => "repeated mesh is probe-lit (the toolkit de-instances it): " + path));
1566
+ checks["repeatRenderers"] = repeats.Count;
1567
+
1568
+ if (options.unfreezeAnimated)
1569
+ {
1570
+ var staticMovers = context.Roots.SelectMany(root => root.GetComponentsInChildren<Transform>(true))
1571
+ .Where(transform => GameObjectUtility.GetStaticEditorFlags(transform.gameObject) != 0 && !IsExcluded(transform, options.exclude))
1572
+ .Select(transform => new { transform, mover = BrowserMoverOf(transform, context) }).Where(entry => entry.mover != null)
1573
+ .Select(entry => PathOf(entry.transform) + " (" + entry.mover + ")").ToList();
1574
+ problems.AddRange(staticMovers.Select(entry => "static but moves in the browser: " + entry));
1575
+ checks["staticMovers"] = staticMovers.Count;
1576
+ }
1577
+
1578
+ var rigType = AnimatorControlRigType();
1579
+ var vatAnimators = rigType == null ? new List<Animator>() : context.All<Animator>().Where(animator => IsVertexAnimated(animator, rigType)).ToList();
1580
+ foreach (var animator in vatAnimators)
1581
+ foreach (var skinned in animator.GetComponentsInChildren<SkinnedMeshRenderer>(true).Where(skinned => skinned.GetComponentInParent<Animator>() == animator))
1582
+ {
1583
+ string path = PathOf(skinned.transform);
1584
+ if (skinned.sharedMaterials.Any(material => material == null || material.shader.name != VertexAnimationShaderName)) problems.Add("VAT crowd member has a material not on " + VertexAnimationShaderName + ": " + path);
1585
+ if (!HasUnitWorldScale(skinned.transform)) problems.Add("VAT crowd member's renderer is not at world scale 1 (it would draw at the wrong size): " + path);
1586
+ if (skinned.lightProbeUsage != LightProbeUsage.Off) problems.Add("VAT crowd member is probe-lit (its copies would not instance): " + path);
1587
+ }
1588
+ checks["vatCrowdMembers"] = vatAnimators.Count;
1589
+
1590
+ string prunedPath = Path.Combine(folder, PrunedCastersFileName);
1591
+ if (File.Exists(prunedPath))
1592
+ {
1593
+ var record = ReadPrunedCasters(prunedPath);
1594
+ foreach (string path in record.paths)
1595
+ {
1596
+ var renderer = context.Renderers.FirstOrDefault(candidate => PathOf(candidate.transform) == path);
1597
+ if (renderer == null) problems.Add("pruned shadow caster is missing: " + path);
1598
+ else if (renderer.shadowCastingMode != ShadowCastingMode.Off) problems.Add("pruned shadow caster casts again: " + path);
1599
+ }
1600
+ checks["prunedCasters"] = record.paths.Length;
1601
+ }
1602
+
1603
+ var copyContributors = GIContributorPaths(scene.GetRootGameObjects());
1604
+ var newContributors = copyContributors.Except(source.contributors).ToList();
1605
+ if (options.keepSourceGI) problems.AddRange(newContributors.Select(path => "--keep-gi: contributes GI but did not in the source: " + path));
1606
+ checks["giContributors"] = new Dictionary<string, object> { { "source", source.contributors.Count }, { "copy", copyContributors.Count }, { "new", newContributors.Count } };
1607
+
1608
+ var md = new StringBuilder("# bt-optimize verify — " + scene.path + "\n\nSource: `" + sourcePath + "`\n\n**Problems: " + problems.Count + "**\n\n");
1609
+ foreach (var problem in problems) md.AppendLine("- " + problem);
1610
+ md.AppendLine("\n## Checks\n");
1611
+ foreach (var check in checks) md.AppendLine("- " + check.Key + ": " + FormatValue(check.Value is Dictionary<string, object> dictionary ? string.Join(", ", dictionary.Select(pair => pair.Key + "=" + pair.Value)) : check.Value));
1612
+ File.WriteAllText(Path.Combine(folder, "verify.md"), md.ToString());
1613
+ File.WriteAllText(Path.Combine(folder, "verify.json"), ToJson(new Dictionary<string, object> { { "scene", scene.path }, { "source", sourcePath },
1614
+ { "problems", problems.Cast<object>().ToList() }, { "checks", checks } }, 0));
1615
+ return "problems=" + problems.Count + "\n" + string.Join("\n", problems.Take(40)) + (problems.Count > 40 ? "\n… (all in verify.md)" : "");
1616
+ }
1617
+
1618
+ /// <summary>
1619
+ /// Reads something from another scene: an open one is read as it is; otherwise it is opened additively, made the
1620
+ /// active scene while it is read (RenderSettings and lighting settings belong to the active scene), and closed unsaved.
1621
+ /// </summary>
1622
+ private static T ReadFromScene<T>(string scenePath, Scene returnTo, Func<Scene, T> read)
1623
+ {
1624
+ var open = SceneManager.GetSceneByPath(scenePath);
1625
+ bool opened = !open.isLoaded;
1626
+ var scene = opened ? EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive) : open;
1627
+ try
1628
+ {
1629
+ SceneManager.SetActiveScene(scene);
1630
+ return read(scene);
1631
+ }
1632
+ finally
1633
+ {
1634
+ SceneManager.SetActiveScene(returnTo);
1635
+ if (opened) EditorSceneManager.CloseScene(scene, true);
1636
+ }
1637
+ }
1638
+
1639
+ /// <summary>Every camera's hierarchy path and whether it renders (enabled on an active object).</summary>
1640
+ private static Dictionary<string, bool> CameraStates(Scene scene)
1641
+ {
1642
+ var states = new Dictionary<string, bool>();
1643
+ foreach (var camera in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(camera => camera.name != PoseCameraName))
1644
+ states[PathOf(camera.transform)] = camera.enabled && camera.gameObject.activeInHierarchy;
1645
+ return states;
1646
+ }
1647
+
1648
+ /// <summary>
1649
+ /// The scene's lighting setup as text, for comparing a copy with its source: the Lighting Settings (mixed mode,
1650
+ /// indirect intensity, albedo boost, lightmapper, resolution), ambient and reflection settings, skybox, fog, and the
1651
+ /// main directional light's mode and shadows. The scene must be the active scene.
1652
+ /// </summary>
1653
+ private static Dictionary<string, string> ReadLighting(Scene scene)
1654
+ {
1655
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
1656
+ var values = new Dictionary<string, string>();
1657
+ LightingSettings settings = null;
1658
+ try { settings = Lightmapping.lightingSettings; } catch (Exception) { /* the scene has no Lighting Settings asset */ }
1659
+ if (settings != null)
1660
+ {
1661
+ values["mixedBakeMode"] = settings.mixedBakeMode.ToString();
1662
+ values["indirectScale"] = settings.indirectScale.ToString("0.###", culture);
1663
+ values["albedoBoost"] = settings.albedoBoost.ToString("0.###", culture);
1664
+ values["lightmapper"] = settings.lightmapper.ToString();
1665
+ values["lightmapResolution"] = settings.lightmapResolution.ToString("0.###", culture);
1666
+ }
1667
+ values["ambientMode"] = RenderSettings.ambientMode.ToString();
1668
+ values["ambientColor"] = RenderSettings.ambientLight.ToString("F3");
1669
+ values["ambientIntensity"] = RenderSettings.ambientIntensity.ToString("0.###", culture);
1670
+ values["reflectionIntensity"] = RenderSettings.reflectionIntensity.ToString("0.###", culture);
1671
+ values["skybox"] = RenderSettings.skybox != null ? RenderSettings.skybox.name : "none";
1672
+ values["fog"] = RenderSettings.fog + " " + RenderSettings.fogMode + " " + RenderSettings.fogColor.ToString("F3");
1673
+ var sun = RenderSettings.sun != null && RenderSettings.sun.gameObject.scene == scene ? RenderSettings.sun
1674
+ : scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Light>(true))
1675
+ .Where(light => light.isActiveAndEnabled && light.type == LightType.Directional).OrderByDescending(light => light.intensity).FirstOrDefault();
1676
+ values["sun"] = sun != null ? sun.name + " " + sun.lightmapBakeType + " shadows " + sun.shadows + " intensity " + sun.intensity.ToString("0.###", culture) : "none";
1677
+ return values;
1678
+ }
1679
+
1680
+ /// <summary>A bake that has not written its LightingData this many seconds after it was started, and is not running, has stopped.</summary>
1681
+ private const long BakeStartGraceSeconds = 120;
1682
+
1683
+ /// <summary>
1684
+ /// Where a bake started at the given time stands, for `wait.mjs cmd` to poll: "baking" while the lightmapper runs,
1685
+ /// "done" once it has stopped and the active scene's LightingData asset was written at or after the start, "stopped"
1686
+ /// when it is not running and wrote nothing more than BakeStartGraceSeconds after the start, "waiting" otherwise.
1687
+ /// `lighting_bake_status` alone can report "completed" before the bake has started.
1688
+ /// </summary>
1689
+ /// <param name="startedUnixSeconds">When bake_lighting was called, in Unix seconds (`date +%s`).</param>
1690
+ public static string BakeState(string startedUnixSeconds)
1691
+ {
1692
+ long started = long.Parse(startedUnixSeconds, System.Globalization.CultureInfo.InvariantCulture);
1693
+ if (Lightmapping.isRunning) return "baking";
1694
+ var data = Lightmapping.lightingDataAsset;
1695
+ string path = data != null ? AssetDatabase.GetAssetPath(data) : "";
1696
+ long written = path.Length > 0 && File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path)).ToUnixTimeSeconds() : 0;
1697
+ if (written >= started) return "done";
1698
+ return DateTimeOffset.UtcNow.ToUnixTimeSeconds() - started > BakeStartGraceSeconds ? "stopped" : "waiting";
1699
+ }
1700
+
1701
+ /// <summary>The name of the capture camera PoseView places.</summary>
1702
+ private const string PoseCameraName = "BtOptimizePoseCamera";
1703
+
795
1704
  /// <summary>
796
1705
  /// Opens the scene (discarding nothing: refuses when the open scene has unsaved changes) and places a capture camera
797
1706
  /// named "BtOptimizePoseCamera" at a pose recorded by the browser profiler (toolkit scenes keep Unity's coordinates),
798
1707
  /// copying the main camera's settings and URP data so post-processing matches. Capture it with
799
- /// `capture_game_view --camera BtOptimizePoseCamera`. The camera is never saved: reopening the scene removes it.
1708
+ /// `capture_game_view --camera BtOptimizePoseCamera`. It never touches the scene's own cameras (a disabled main camera
1709
+ /// that got saved once shipped a game with no post-processing): the pose camera renders above them by depth and is
1710
+ /// flagged DontSaveInEditor, so it is never written to the scene. Reopen the scene before exporting — the exporter
1711
+ /// would otherwise see it as one more camera.
800
1712
  /// </summary>
801
1713
  public static string PoseView(string scenePath, float px, float py, float pz, float qx, float qy, float qz, float qw, float verticalFovRadians)
802
1714
  {
@@ -804,15 +1716,15 @@ public static class BtOptimize
804
1716
  if (active.path != scenePath)
805
1717
  {
806
1718
  // The only unsaved change PoseView allows itself to discard is its own pose camera.
807
- bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == "BtOptimizePoseCamera");
1719
+ bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == PoseCameraName);
808
1720
  if (active.isDirty && !onlyPoseCamera) throw new InvalidOperationException("'" + active.path + "' has unsaved changes; save or discard them first.");
809
1721
  EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
810
1722
  }
811
1723
  var scene = SceneManager.GetActiveScene();
812
- var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == "BtOptimizePoseCamera");
1724
+ var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == PoseCameraName);
813
1725
  if (existing != null) UnityEngine.Object.DestroyImmediate(existing);
814
1726
  var main = Camera.main;
815
- var go = new GameObject("BtOptimizePoseCamera");
1727
+ var go = new GameObject(PoseCameraName) { hideFlags = HideFlags.DontSaveInEditor };
816
1728
  var camera = go.AddComponent<Camera>();
817
1729
  if (main != null)
818
1730
  {
@@ -823,8 +1735,11 @@ public static class BtOptimize
823
1735
  var data = go.GetComponent(mainData.GetType()) ?? go.AddComponent(mainData.GetType());
824
1736
  EditorUtility.CopySerialized(mainData, data);
825
1737
  }
826
- main.enabled = false;
827
1738
  }
1739
+ // Render above every scene camera instead of disabling any of them: the scene's cameras are never changed.
1740
+ var sceneCameras = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(other => other != camera).ToList();
1741
+ camera.depth = sceneCameras.Count > 0 ? sceneCameras.Max(other => other.depth) + 1f : camera.depth;
1742
+ foreach (var component in go.GetComponents<Component>()) component.hideFlags = HideFlags.DontSaveInEditor;
828
1743
  go.transform.SetPositionAndRotation(new Vector3(px, py, pz), new Quaternion(qx, qy, qz, qw));
829
1744
  camera.fieldOfView = verticalFovRadians * Mathf.Rad2Deg;
830
1745
  camera.enabled = true;
@@ -916,8 +1831,8 @@ public static class BtOptimize
916
1831
  /// <summary>
917
1832
  /// Why the renderer is not a visible, lightmappable surface, or null. Only shaders with a lightmapper Meta pass
918
1833
  /// (URP Lit / Simple Lit / Unlit, Built-in Standard, Shader Graph Lit / Unlit…) describe a surface to the bake.
919
- /// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, Garden's invisible
920
- /// `Room1Screens` stencil mesh (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
1834
+ /// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, an invisible stencil mesh
1835
+ /// (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
921
1836
  /// room went dark.
922
1837
  /// </summary>
923
1838
  private static string NotAVisibleSurface(Renderer renderer)
@@ -975,6 +1890,8 @@ public static class BtOptimize
975
1890
  private sealed class SkinningVerdict
976
1891
  {
977
1892
  public string Kind, Why;
1893
+ /// <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>
1894
+ public bool OffsetBaked;
978
1895
  public Matrix4x4 MeshToObject = Matrix4x4.identity;
979
1896
  /// <summary>Where the skinning draws the mesh: bone × bind pose (mesh space to world space).</summary>
980
1897
  public Matrix4x4 MeshToWorld = Matrix4x4.identity;
@@ -997,26 +1914,86 @@ public static class BtOptimize
997
1914
  if (weightedBoneIndices.Count > 1)
998
1915
  {
999
1916
  string movedBone = weightedBoneIndices.Select(index => SeparateMotionBetween(bones[index], renderer.transform, context)).FirstOrDefault(motion => motion != null);
1000
- return movedBone != null
1001
- ? new SkinningVerdict(SkinDeforms, weightedBoneIndices.Count + " weighted bones; " + movedBone)
1917
+ if (movedBone != null) return new SkinningVerdict(SkinDeforms, weightedBoneIndices.Count + " weighted bones; " + movedBone);
1918
+ string poseBlocker = ConversionBlocker(renderer, context);
1919
+ return poseBlocker != null
1920
+ ? new SkinningVerdict(SkinRigidByHand, weightedBoneIndices.Count + " weighted bones that never move, but " + poseBlocker)
1002
1921
  : new SkinningVerdict(SkinFrozenPose, weightedBoneIndices.Count + " weighted bones, none moved by a clip, Timeline or script");
1003
1922
  }
1004
1923
  if (weightedBoneIndices.Count == 0 || mesh.bindposes.Length <= weightedBoneIndices[0]) return new SkinningVerdict(SkinRigidByHand, "no usable bone weights or bind poses");
1005
1924
  int boneIndex = weightedBoneIndices[0];
1006
1925
  var bone = bones[boneIndex];
1007
1926
  string separateMotion = SeparateMotionBetween(bone, renderer.transform, context);
1008
- if (separateMotion != null) return new SkinningVerdict(SkinRigidByHand, "one bone, but it may move apart from the object (" + separateMotion + "): parent a plain mesh under '" + bone.name + "'");
1009
- if (context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve)) return new SkinningVerdict(SkinRigidByHand, "a clip animates the SkinnedMeshRenderer itself (" + curve + "): retarget the curve to MeshRenderer");
1010
- if (context.ReferencedComponents.Contains(renderer)) return new SkinningVerdict(SkinRigidByHand, "a component references the SkinnedMeshRenderer itself");
1927
+ bool scriptHost = separateMotion != null && IsOnlyScriptOnRenderer(renderer, bone, context);
1928
+ 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 + "'");
1929
+ string blocker = ConversionBlocker(renderer, context);
1930
+ if (blocker != null) return new SkinningVerdict(SkinRigidByHand, "one bone ('" + bone.name + "'), but " + blocker);
1931
+ string curveNote = context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve) ? "; a clip animates the SkinnedMeshRenderer itself (" + curve + ")" : "";
1932
+ if (scriptHost) return new SkinningVerdict(SkinRigidScriptHost, "one bone ('" + bone.name + "'); the only separate motion is " + separateMotion + ", on the renderer's own object" + curveNote);
1011
1933
  // A one-bone vertex is drawn at bone × bindpose × vertex; a MeshFilter draws it at object × vertex. The fixed
1012
1934
  // difference between the two, in the object's space, is all the skinning does.
1013
1935
  var meshToWorld = bone.localToWorldMatrix * mesh.bindposes[boneIndex];
1014
1936
  var meshToObject = renderer.transform.worldToLocalMatrix * meshToWorld;
1015
1937
  float offset = LargestVertexOffset(mesh, meshToObject, renderer.transform.lossyScale);
1016
- string evidence = "one bone ('" + bone.name + "') moving with the object, no blend shapes or cloth";
1017
- if (offset <= RestPoseTolerance(renderer)) return new SkinningVerdict(SkinRigid, evidence + ", bind pose within " + offset.ToString("0.####") + " units");
1018
- return new SkinningVerdict(SkinRigidOffset, evidence + "; the bind pose offsets the mesh by up to " + offset.ToString("0.###") + " units")
1019
- { MeshToObject = meshToObject, MeshToWorld = meshToWorld };
1938
+ bool offsetBaked = offset > RestPoseTolerance(renderer);
1939
+ string evidence = "one bone ('" + bone.name + "') moving with the object, no blend shapes or cloth"
1940
+ + (offsetBaked ? "; the bind pose offsets the mesh by up to " + offset.ToString("0.###") + " units" : ", bind pose within " + offset.ToString("0.####") + " units");
1941
+ string kind = offsetBaked ? SkinRigidOffset : SkinRigid;
1942
+ if (curveNote.Length > 0) kind = SkinRigidRendererCurves;
1943
+ var verdict = new SkinningVerdict(kind, evidence + curveNote) { OffsetBaked = offsetBaked };
1944
+ if (!offsetBaked) return verdict;
1945
+ verdict.MeshToObject = meshToObject;
1946
+ verdict.MeshToWorld = meshToWorld;
1947
+ return verdict;
1948
+ }
1949
+
1950
+ /// <summary>
1951
+ /// Why a skinned renderer whose bones move with it still cannot be converted automatically, or null: a component
1952
+ /// references the SkinnedMeshRenderer itself, or a clip Tune cannot retarget animates it.
1953
+ /// </summary>
1954
+ private static string ConversionBlocker(SkinnedMeshRenderer renderer, Context context)
1955
+ {
1956
+ if (context.ReferencedComponents.Contains(renderer)) return "a component references the SkinnedMeshRenderer itself";
1957
+ return RendererCurveBlocker(renderer, context);
1958
+ }
1959
+
1960
+ /// <summary>
1961
+ /// Why the clips that animate this SkinnedMeshRenderer cannot be retargeted to MeshRenderer, or null (also when no
1962
+ /// clip animates it). Only an Animator playing a plain AnimatorController can be given a retargeted copy.
1963
+ /// </summary>
1964
+ private static string RendererCurveBlocker(SkinnedMeshRenderer renderer, Context context)
1965
+ {
1966
+ if (!context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve)) return null;
1967
+ foreach (var animation in renderer.GetComponentsInParent<Animation>(true))
1968
+ if (AnimationUtility.GetAnimationClips(animation.gameObject).Any(clip => AnimatesRenderer(clip, animation.transform, renderer.transform)))
1969
+ return "a legacy Animation on '" + animation.name + "' animates it (" + curve + "): retarget the curve to MeshRenderer by hand";
1970
+ foreach (var animator in renderer.GetComponentsInParent<Animator>(true))
1971
+ {
1972
+ var controller = animator.runtimeAnimatorController;
1973
+ if (controller == null || controller is UnityEditor.Animations.AnimatorController) continue;
1974
+ if (controller.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, renderer.transform)))
1975
+ return "the Animator on '" + animator.name + "' animates it through a " + controller.GetType().Name + " (" + curve + "): retarget the curve to MeshRenderer by hand";
1976
+ }
1977
+ return null;
1978
+ }
1979
+
1980
+ /// <summary>
1981
+ /// True when the only separate motion between the bone and the renderer's object is a toolkit script on that object
1982
+ /// itself: no clip, Timeline, constraint, Rigidbody or script on either chain up to their common ancestor, and the
1983
+ /// renderer's own object has an EditorScriptComponent but is not animated and has no constraint or Rigidbody.
1984
+ /// </summary>
1985
+ private static bool IsOnlyScriptOnRenderer(SkinnedMeshRenderer renderer, Transform bone, Context context)
1986
+ {
1987
+ var rendererTransform = renderer.transform;
1988
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
1989
+ if (rendererTransform == commonAncestor) return false;
1990
+ var otherLinks = ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform.parent, commonAncestor));
1991
+ if (otherLinks.Any(node => MotionOn(node, context) != null)) return false;
1992
+ if (context.AnimatedTransforms.ContainsKey(rendererTransform)) return false;
1993
+ var components = rendererTransform.GetComponents<Component>();
1994
+ bool hasScript = components.Any(component => component is EditorScriptComponent);
1995
+ bool hasPhysicsOrConstraint = components.Any(component => component is Rigidbody || component is UnityEngine.Animations.IConstraint);
1996
+ return hasScript && !hasPhysicsOrConstraint;
1020
1997
  }
1021
1998
 
1022
1999
  /// <summary>How far, in world units, a converted vertex may land from where the skinning drew it.</summary>
@@ -1083,8 +2060,7 @@ public static class BtOptimize
1083
2060
  /// </summary>
1084
2061
  private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
1085
2062
  {
1086
- string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], OffsetKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1087
- string cacheKey = source.GetHashCode() + "|" + offsetKey;
2063
+ string cacheKey = source.GetHashCode() + "|" + OffsetKey(meshToObject);
1088
2064
  if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
1089
2065
  var baked = UnityEngine.Object.Instantiate(source);
1090
2066
  baked.name = source.name + "_Unskinned_" + bakedMeshes.Count;
@@ -1104,14 +2080,19 @@ public static class BtOptimize
1104
2080
  baked.boneWeights = new BoneWeight[0];
1105
2081
  baked.bindposes = new Matrix4x4[0];
1106
2082
  baked.RecalculateBounds();
1107
- if (!AssetDatabase.IsValidFolder(folder)) AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), Path.GetFileName(folder));
1108
- AssetDatabase.CreateAsset(baked, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + baked.name + ".asset"));
2083
+ CreateMeshAsset(baked, folder);
1109
2084
  bakedMeshes[cacheKey] = baked;
1110
2085
  return baked;
1111
2086
  }
1112
2087
 
2088
+ /// <summary>A bind-pose offset matrix as text, rounded to SharedMeshKeyDecimals: copies with equal keys share one baked mesh.</summary>
2089
+ private static string OffsetKey(Matrix4x4 meshToObject)
2090
+ {
2091
+ return string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
2092
+ }
2093
+
1113
2094
  /// <summary>
1114
- /// Folder for meshes baked from offset rigid skinned meshes: &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
2095
+ /// Folder for meshes baked from skinned meshes (offset rigid meshes and baked poses): &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1115
2096
  /// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
1116
2097
  /// </summary>
1117
2098
  private static string UnskinnedMeshFolder(Scene scene)
@@ -1119,32 +2100,331 @@ public static class BtOptimize
1119
2100
  return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_UnskinnedMeshes";
1120
2101
  }
1121
2102
 
2103
+ /// <summary>Folder for clips and controllers copied with their SkinnedMeshRenderer curves retargeted: &lt;scene folder&gt;/&lt;scene&gt;_RetargetedClips.</summary>
2104
+ private static string RetargetedClipFolder(Scene scene)
2105
+ {
2106
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_RetargetedClips";
2107
+ }
2108
+
2109
+ /// <summary>Creates the project folder (one level below an existing folder) when it is missing.</summary>
2110
+ private static void EnsureFolder(string folder)
2111
+ {
2112
+ if (!AssetDatabase.IsValidFolder(folder)) AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), Path.GetFileName(folder));
2113
+ }
2114
+
2115
+ /// <summary>Saves the mesh as a new asset named after it in the folder (a unique path when the name is taken).</summary>
2116
+ private static void CreateMeshAsset(Mesh mesh, string folder)
2117
+ {
2118
+ EnsureFolder(folder);
2119
+ AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + mesh.name + ".asset"));
2120
+ }
2121
+
2122
+ /// <summary>
2123
+ /// The renderer's current skinned shape as a plain mesh in its object's space, shared by every renderer with the same
2124
+ /// source mesh and baked vertices (rounded to SharedMeshKeyDecimals) so the copies still instance. Saved in the
2125
+ /// folder unless `save` is false (a dry run, which only compares shapes; see DiscardUnsavedMeshes).
2126
+ /// </summary>
2127
+ private static Mesh BakedPoseMesh(SkinnedMeshRenderer skinned, string folder, Dictionary<string, Mesh> bakedMeshes, bool save, out string howPlaced)
2128
+ {
2129
+ var source = skinned.sharedMesh;
2130
+ var baked = BakePoseToObjectSpace(skinned);
2131
+ string shapeKey = PoseShapeKey(source, baked);
2132
+ if (bakedMeshes.TryGetValue(shapeKey, out var existing))
2133
+ {
2134
+ UnityEngine.Object.DestroyImmediate(baked);
2135
+ baked = existing;
2136
+ }
2137
+ else
2138
+ {
2139
+ string namePrefix = source.name + "_Pose_";
2140
+ baked.name = namePrefix + bakedMeshes.Values.Count(mesh => mesh.name.StartsWith(namePrefix, StringComparison.Ordinal));
2141
+ if (save) CreateMeshAsset(baked, folder);
2142
+ bakedMeshes[shapeKey] = baked;
2143
+ }
2144
+ string assetPath = EditorUtility.IsPersistent(baked) ? AssetDatabase.GetAssetPath(baked) : folder + "/" + baked.name + ".asset";
2145
+ howPlaced = "baked pose, shared mesh asset " + assetPath;
2146
+ return baked;
2147
+ }
2148
+
2149
+ /// <summary>
2150
+ /// A copy of the renderer's mesh with linear-blend skinning applied at the current bone pose, expressed in the
2151
+ /// renderer object's local space (what a MeshFilter on that object must draw), with the skin data removed. A vertex
2152
+ /// with no weights keeps its position.
2153
+ /// </summary>
2154
+ private static Mesh BakePoseToObjectSpace(SkinnedMeshRenderer skinned)
2155
+ {
2156
+ var source = skinned.sharedMesh;
2157
+ var boneToObject = BoneToObjectMatrices(skinned);
2158
+ var normalMatrices = boneToObject.Select(matrix => matrix.inverse.transpose).ToArray();
2159
+ var bonesPerVertex = source.GetBonesPerVertex();
2160
+ var weights = source.GetAllBoneWeights();
2161
+ var vertices = source.vertices;
2162
+ var normals = source.normals;
2163
+ var tangents = source.tangents;
2164
+ int weightIndex = 0;
2165
+ for (int i = 0; i < vertices.Length; i++)
2166
+ {
2167
+ Vector3 position = Vector3.zero, normal = Vector3.zero, tangent = Vector3.zero;
2168
+ int influenceCount = bonesPerVertex[i];
2169
+ for (int j = 0; j < influenceCount; j++, weightIndex++)
2170
+ {
2171
+ var influence = weights[weightIndex];
2172
+ position += influence.weight * boneToObject[influence.boneIndex].MultiplyPoint3x4(vertices[i]);
2173
+ if (normals.Length > 0) normal += influence.weight * normalMatrices[influence.boneIndex].MultiplyVector(normals[i]);
2174
+ if (tangents.Length > 0) tangent += influence.weight * boneToObject[influence.boneIndex].MultiplyVector(tangents[i]);
2175
+ }
2176
+ if (influenceCount == 0) continue;
2177
+ vertices[i] = position;
2178
+ if (normals.Length > 0) normals[i] = normal.normalized;
2179
+ if (tangents.Length > 0)
2180
+ {
2181
+ var direction = tangent.normalized;
2182
+ tangents[i] = new Vector4(direction.x, direction.y, direction.z, tangents[i].w);
2183
+ }
2184
+ }
2185
+ var baked = UnityEngine.Object.Instantiate(source);
2186
+ baked.boneWeights = new BoneWeight[0];
2187
+ baked.bindposes = new Matrix4x4[0];
2188
+ baked.vertices = vertices;
2189
+ if (normals.Length > 0) baked.normals = normals;
2190
+ if (tangents.Length > 0) baked.tangents = tangents;
2191
+ baked.RecalculateBounds();
2192
+ return baked;
2193
+ }
2194
+
2195
+ /// <summary>For each bone: object-from-world × bone-to-world × bind pose (identity for a missing bone or bind pose).</summary>
2196
+ private static Matrix4x4[] BoneToObjectMatrices(SkinnedMeshRenderer skinned)
2197
+ {
2198
+ var bones = skinned.bones;
2199
+ var bindposes = skinned.sharedMesh.bindposes;
2200
+ var worldToObject = skinned.transform.worldToLocalMatrix;
2201
+ var matrices = new Matrix4x4[bones.Length];
2202
+ for (int i = 0; i < bones.Length; i++)
2203
+ matrices[i] = bones[i] != null && i < bindposes.Length ? worldToObject * bones[i].localToWorldMatrix * bindposes[i] : Matrix4x4.identity;
2204
+ return matrices;
2205
+ }
2206
+
2207
+ /// <summary>Identifies a baked shape: the source mesh plus its vertex positions rounded to SharedMeshKeyDecimals.</summary>
2208
+ private static string PoseShapeKey(Mesh source, Mesh baked)
2209
+ {
2210
+ string format = "F" + SharedMeshKeyDecimals;
2211
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
2212
+ var rounded = baked.vertices.Select(vertex => vertex.x.ToString(format, culture) + "," + vertex.y.ToString(format, culture) + "," + vertex.z.ToString(format, culture));
2213
+ return "pose|" + source.GetHashCode() + "|" + string.Join(";", rounded).GetHashCode();
2214
+ }
2215
+
2216
+ // ------------------------------------------------------------------------------------------------------------
2217
+ // Renderer curves — clips that animate a SkinnedMeshRenderer, retargeted to the MeshRenderer that replaces it
2218
+ // ------------------------------------------------------------------------------------------------------------
2219
+
2220
+ /// <summary>The clip's float and object-reference curve bindings that target a SkinnedMeshRenderer.</summary>
2221
+ private static List<EditorCurveBinding> RendererBindings(AnimationClip clip)
2222
+ {
2223
+ return AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip))
2224
+ .Where(binding => binding.type == typeof(SkinnedMeshRenderer)).ToList();
2225
+ }
2226
+
2227
+ /// <summary>The transform a curve binding targets, resolved from the animated root, or null.</summary>
2228
+ private static Transform ResolveBinding(Transform animatedRoot, EditorCurveBinding binding)
2229
+ {
2230
+ return binding.path == "" ? animatedRoot : animatedRoot.Find(binding.path);
2231
+ }
2232
+
2233
+ /// <summary>True when the clip, played from the animated root, animates the SkinnedMeshRenderer on the target.</summary>
2234
+ private static bool AnimatesRenderer(AnimationClip clip, Transform animatedRoot, Transform target)
2235
+ {
2236
+ return clip != null && RendererBindings(clip).Any(binding => ResolveBinding(animatedRoot, binding) == target);
2237
+ }
2238
+
2239
+ /// <summary>The Animators on or above the renderer whose controller's clips animate that SkinnedMeshRenderer.</summary>
2240
+ private static List<Animator> AnimatorsWithRendererCurves(SkinnedMeshRenderer skinned)
2241
+ {
2242
+ return skinned.GetComponentsInParent<Animator>(true)
2243
+ .Where(animator => animator.runtimeAnimatorController is UnityEditor.Animations.AnimatorController)
2244
+ .Where(animator => animator.runtimeAnimatorController.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, skinned.transform)))
2245
+ .ToList();
2246
+ }
2247
+
2248
+ /// <summary>Names, for the report, each clip that will be copied with its curves retargeted and the controller copy that plays it.</summary>
2249
+ private static string RetargetPlan(List<Animator> animators, Transform target, string folder)
2250
+ {
2251
+ var plans = animators.Select(animator =>
2252
+ {
2253
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
2254
+ var clipNames = controller.animationClips.Where(clip => AnimatesRenderer(clip, animator.transform, target)).Select(clip => "'" + clip.name + "'").Distinct();
2255
+ return "clip " + string.Join(", ", clipNames) + " copied with its SkinnedMeshRenderer curves aimed at MeshRenderer, played by controller copy "
2256
+ + RetargetedControllerPath(controller, folder) + " (Animator on " + animator.name + ")";
2257
+ });
2258
+ return string.Join("; ", plans);
2259
+ }
2260
+
2261
+ /// <summary>Where the retargeted copy of a controller is saved.</summary>
2262
+ private static string RetargetedControllerPath(UnityEditor.Animations.AnimatorController controller, string folder)
2263
+ {
2264
+ return folder + "/" + controller.name + "_MeshRenderer.controller";
2265
+ }
2266
+
2267
+ /// <summary>
2268
+ /// Gives each Animator a copy of its controller whose clips aim every SkinnedMeshRenderer curve at a converted object
2269
+ /// (one that now has a MeshRenderer) at MeshRenderer instead, same path and property. Animators sharing a controller
2270
+ /// share its copy. The original clips and controllers are never edited; only the Animators in this scene change.
2271
+ /// </summary>
2272
+ private static void RetargetAnimators(List<Animator> animators, string folder)
2273
+ {
2274
+ var controllerCopies = new Dictionary<UnityEditor.Animations.AnimatorController, UnityEditor.Animations.AnimatorController>();
2275
+ var clipCopies = new Dictionary<AnimationClip, AnimationClip>();
2276
+ foreach (var animator in animators)
2277
+ {
2278
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
2279
+ if (!controllerCopies.TryGetValue(controller, out var copy))
2280
+ {
2281
+ copy = RetargetedController(controller, animator.transform, folder, clipCopies);
2282
+ controllerCopies[controller] = copy;
2283
+ }
2284
+ animator.runtimeAnimatorController = copy;
2285
+ EditorUtility.SetDirty(animator);
2286
+ }
2287
+ }
2288
+
2289
+ /// <summary>
2290
+ /// A fresh copy of the controller (replacing a copy an earlier run left) with every clip that has retargeted curves
2291
+ /// swapped for its copy, in every state and blend tree of every layer.
2292
+ /// </summary>
2293
+ private static UnityEditor.Animations.AnimatorController RetargetedController(UnityEditor.Animations.AnimatorController controller, Transform animatedRoot,
2294
+ string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
2295
+ {
2296
+ EnsureFolder(folder);
2297
+ string copyPath = RetargetedControllerPath(controller, folder);
2298
+ AssetDatabase.DeleteAsset(copyPath);
2299
+ if (!AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(controller), copyPath)) throw new InvalidOperationException("Could not copy " + controller.name + " to " + copyPath);
2300
+ var copy = AssetDatabase.LoadAssetAtPath<UnityEditor.Animations.AnimatorController>(copyPath);
2301
+ var replacements = new Dictionary<AnimationClip, AnimationClip>();
2302
+ foreach (var clip in controller.animationClips.Where(clip => clip != null).Distinct())
2303
+ {
2304
+ var retargeted = RetargetedClip(clip, animatedRoot, folder, clipCopies);
2305
+ if (retargeted != null) replacements[clip] = retargeted;
2306
+ }
2307
+ foreach (var layer in copy.layers) ReplaceMotions(layer.stateMachine, replacements);
2308
+ EditorUtility.SetDirty(copy);
2309
+ return copy;
2310
+ }
2311
+
2312
+ /// <summary>
2313
+ /// A copy of the clip with every SkinnedMeshRenderer curve whose target now has a MeshRenderer retargeted to
2314
+ /// MeshRenderer (same path and property), saved in the folder as &lt;clip&gt;_MeshRenderer.anim (an earlier run's copy
2315
+ /// is updated in place). Null when the clip has no such curve. Each clip is copied once per run.
2316
+ /// </summary>
2317
+ private static AnimationClip RetargetedClip(AnimationClip clip, Transform animatedRoot, string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
2318
+ {
2319
+ if (clipCopies.TryGetValue(clip, out var done)) return done;
2320
+ var bindings = RendererBindings(clip).Where(binding => ResolveBinding(animatedRoot, binding) is Transform target && target.GetComponent<MeshRenderer>() != null).ToList();
2321
+ if (bindings.Count == 0) return null;
2322
+ var retargeted = UnityEngine.Object.Instantiate(clip);
2323
+ retargeted.name = clip.name + "_MeshRenderer";
2324
+ foreach (var binding in bindings) RetargetBinding(clip, retargeted, binding);
2325
+ string clipPath = folder + "/" + retargeted.name + ".anim";
2326
+ var previous = AssetDatabase.LoadAssetAtPath<AnimationClip>(clipPath);
2327
+ if (previous == null)
2328
+ {
2329
+ AssetDatabase.CreateAsset(retargeted, clipPath);
2330
+ }
2331
+ else
2332
+ {
2333
+ EditorUtility.CopySerialized(retargeted, previous);
2334
+ UnityEngine.Object.DestroyImmediate(retargeted);
2335
+ retargeted = previous;
2336
+ }
2337
+ clipCopies[clip] = retargeted;
2338
+ return retargeted;
2339
+ }
2340
+
2341
+ /// <summary>Moves one curve of the copied clip from the SkinnedMeshRenderer binding to the same MeshRenderer binding.</summary>
2342
+ private static void RetargetBinding(AnimationClip source, AnimationClip retargeted, EditorCurveBinding binding)
2343
+ {
2344
+ var meshBinding = binding;
2345
+ meshBinding.type = typeof(MeshRenderer);
2346
+ if (binding.isPPtrCurve)
2347
+ {
2348
+ var keyframes = AnimationUtility.GetObjectReferenceCurve(source, binding);
2349
+ AnimationUtility.SetObjectReferenceCurve(retargeted, binding, null);
2350
+ AnimationUtility.SetObjectReferenceCurve(retargeted, meshBinding, keyframes);
2351
+ return;
2352
+ }
2353
+ var curve = AnimationUtility.GetEditorCurve(source, binding);
2354
+ AnimationUtility.SetEditorCurve(retargeted, binding, null);
2355
+ AnimationUtility.SetEditorCurve(retargeted, meshBinding, curve);
2356
+ }
2357
+
2358
+ /// <summary>Swaps state motions in the state machine (and its sub-state machines) for their replacements.</summary>
2359
+ private static void ReplaceMotions(UnityEditor.Animations.AnimatorStateMachine stateMachine, Dictionary<AnimationClip, AnimationClip> replacements)
2360
+ {
2361
+ foreach (var child in stateMachine.states) child.state.motion = ReplacedMotion(child.state.motion, replacements);
2362
+ foreach (var child in stateMachine.stateMachines) ReplaceMotions(child.stateMachine, replacements);
2363
+ }
2364
+
2365
+ /// <summary>The motion with every replaced clip swapped in: the clip's replacement, or a blend tree with its children swapped.</summary>
2366
+ private static Motion ReplacedMotion(Motion motion, Dictionary<AnimationClip, AnimationClip> replacements)
2367
+ {
2368
+ if (motion is AnimationClip clip) return replacements.TryGetValue(clip, out var replacement) ? replacement : clip;
2369
+ if (!(motion is UnityEditor.Animations.BlendTree blendTree)) return motion;
2370
+ var children = blendTree.children;
2371
+ for (int i = 0; i < children.Length; i++) children[i].motion = ReplacedMotion(children[i].motion, replacements);
2372
+ blendTree.children = children;
2373
+ return blendTree;
2374
+ }
2375
+
1122
2376
  /// <summary>
1123
2377
  /// What moves the bone relative to the renderer's object, or null when the two always move together. Only the
1124
2378
  /// transforms between each of them and their nearest common ancestor count: whatever moves that ancestor (an
1125
2379
  /// Animator popping the whole prop in, a script spinning it) moves bone and mesh alike.
1126
2380
  /// </summary>
1127
2381
  private static string SeparateMotionBetween(Transform bone, Transform rendererTransform, Context context)
2382
+ {
2383
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
2384
+ return ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform, commonAncestor))
2385
+ .Select(node => MotionOn(node, context)).FirstOrDefault(motion => motion != null);
2386
+ }
2387
+
2388
+ /// <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>
2389
+ private static Transform CommonAncestor(Transform bone, Transform rendererTransform)
1128
2390
  {
1129
2391
  var rendererAncestors = new HashSet<Transform>();
1130
2392
  for (var node = rendererTransform; node != null; node = node.parent) rendererAncestors.Add(node);
1131
2393
  var commonAncestor = bone;
1132
2394
  while (commonAncestor != null && !rendererAncestors.Contains(commonAncestor)) commonAncestor = commonAncestor.parent;
1133
- foreach (var start in new[] { bone, rendererTransform })
1134
- for (var node = start; node != null && node != commonAncestor; node = node.parent)
1135
- {
1136
- if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return "'" + node.name + "' is animated by " + animator;
1137
- foreach (var component in node.GetComponents<Component>())
1138
- if (component is EditorScriptComponent || component is Rigidbody || component is UnityEngine.Animations.IConstraint)
1139
- return "'" + node.name + "' has " + component.GetType().Name;
1140
- }
2395
+ return commonAncestor;
2396
+ }
2397
+
2398
+ /// <summary>The transform and its ancestors up to, but not including, the ancestor (empty when start is null or the ancestor).</summary>
2399
+ private static IEnumerable<Transform> ChainBelow(Transform start, Transform ancestor)
2400
+ {
2401
+ for (var node = start; node != null && node != ancestor; node = node.parent) yield return node;
2402
+ }
2403
+
2404
+ /// <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>
2405
+ private static string MotionOn(Transform node, Context context)
2406
+ {
2407
+ if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return "'" + node.name + "' is animated by " + animator;
2408
+ foreach (var component in node.GetComponents<Component>())
2409
+ if (component is EditorScriptComponent || component is Rigidbody || component is UnityEngine.Animations.IConstraint)
2410
+ return "'" + node.name + "' has " + component.GetType().Name;
1141
2411
  return null;
1142
2412
  }
1143
2413
 
1144
2414
  /// <summary>True when the renderer's mesh and materials repeat often enough that its copies should share an instanced draw.</summary>
1145
2415
  private static bool IsRepeatedForInstancing(Renderer renderer, Context context, TuneOptions options)
1146
2416
  {
1147
- return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) && copies >= options.instanceRepeatsFrom;
2417
+ return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKeyOf(renderer, context), out var copies) && copies >= options.instanceRepeatsFrom;
2418
+ }
2419
+
2420
+ /// <summary>
2421
+ /// RepeatKey, except that a skinned renderer a dry run plans to convert is keyed by the mesh it will draw
2422
+ /// (see PlannedMeshKey) rather than the skinned mesh it draws now.
2423
+ /// </summary>
2424
+ private static string RepeatKeyOf(Renderer renderer, Context context)
2425
+ {
2426
+ if (!(renderer is SkinnedMeshRenderer skinned) || !context.PlannedMeshKeys.TryGetValue(skinned, out var plannedMesh)) return RepeatKey(renderer);
2427
+ return "planned " + plannedMesh + "|" + string.Join(",", renderer.sharedMaterials.Select(material => material != null ? material.GetHashCode() : 0));
1148
2428
  }
1149
2429
 
1150
2430
  /// <summary>
@@ -1205,9 +2485,24 @@ public static class BtOptimize
1205
2485
  public readonly HashSet<Component> ReferencedComponents;
1206
2486
  /// <summary>How many active renderers draw each mesh + materials combination (see RepeatKey).</summary>
1207
2487
  public readonly Dictionary<string, int> RepeatCounts;
2488
+ /// <summary>Hierarchy paths of the renderers that contribute GI in the source scene (Tune only; empty for a survey).</summary>
2489
+ public readonly HashSet<string> SourceGIContributors;
2490
+ /// <summary>
2491
+ /// Hierarchy paths of the renderers that contribute GI once Tune's changes land. Starts as the scene's own set;
2492
+ /// the steps keep it in step with the Contribute GI flags they add or clear, so a dry run can count it too.
2493
+ /// </summary>
2494
+ public readonly HashSet<string> PlannedGIContributors;
2495
+ /// <summary>Skinned renderers a dry run plans to convert: later steps treat them as the MeshRenderers they become.</summary>
2496
+ public readonly List<SkinnedMeshRenderer> PlannedUnskinned = new List<SkinnedMeshRenderer>();
2497
+ /// <summary>For each renderer a dry run plans to convert, the identity of the mesh it will draw (see PlannedMeshKey).</summary>
2498
+ public readonly Dictionary<SkinnedMeshRenderer, string> PlannedMeshKeys = new Dictionary<SkinnedMeshRenderer, string>();
2499
+ /// <summary>Objects whose static flags Tune clears (UnfreezeAnimated); a dry run's later steps treat them as non-static.</summary>
2500
+ public readonly HashSet<GameObject> PlannedNonStatic = new HashSet<GameObject>();
1208
2501
  public readonly StringBuilder Summary = new StringBuilder();
1209
2502
 
1210
- public Context(Scene scene)
2503
+ /// <param name="scene">The scene to gather.</param>
2504
+ /// <param name="sourceGIContributors">Tune's source contributor set (see SourceGIContributorsOf); null for a survey.</param>
2505
+ public Context(Scene scene, HashSet<string> sourceGIContributors = null)
1211
2506
  {
1212
2507
  Scene = scene;
1213
2508
  Roots = scene.GetRootGameObjects().ToList();
@@ -1221,6 +2516,8 @@ public static class BtOptimize
1221
2516
  CollectAnimationTargets(this);
1222
2517
  ReferencedComponents = CollectReferencedComponents(Roots);
1223
2518
  RepeatCounts = Renderers.GroupBy(RepeatKey).ToDictionary(group => group.Key, group => group.Count());
2519
+ SourceGIContributors = sourceGIContributors ?? new HashSet<string>();
2520
+ PlannedGIContributors = GIContributorPaths(Roots);
1224
2521
  }
1225
2522
 
1226
2523
  /// <summary>Every component of type T in the scene, including inactive objects.</summary>