@babylonjs-toolkit/agent 1.2.11 → 1.2.14

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.
@@ -94,6 +94,7 @@ public static class BtOptimize
94
94
  SurveyRenderers(context, md, json);
95
95
  SurveySkinning(context, md, json);
96
96
  SurveyRepeats(context, md, json);
97
+ SurveyShadowCasters(context, md, json);
97
98
  SurveyPostProcessing(context, md, json);
98
99
  SurveyPipeline(md, json);
99
100
  SurveyExporter(context, md, json);
@@ -297,9 +298,100 @@ public static class BtOptimize
297
298
  int lightmapped = renderers.OfType<MeshRenderer>().Count(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
298
299
  && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
299
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)");
300
304
  return blockers;
301
305
  }
302
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
+
303
395
  /// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
304
396
  private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
305
397
  {
@@ -344,6 +436,10 @@ public static class BtOptimize
344
436
  + " HDR=" + camera.allowHDR + " MSAA=" + camera.allowMSAA + " far=" + camera.farClipPlane);
345
437
  cameras.Add(new Dictionary<string, object> { { "path", PathOf(camera.transform) }, { "enabled", camera.isActiveAndEnabled }, { "antialiasing", aa }, { "antialiasingQuality", aaQuality }, { "postProcessing", post }, { "far", camera.farClipPlane } });
346
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" : "") + ".");
347
443
  md.AppendLine();
348
444
  json["volumes"] = volumes;
349
445
  json["cameras"] = cameras;
@@ -445,7 +541,7 @@ public static class BtOptimize
445
541
  /// <summary>
446
542
  /// Also bake lights that cast realtime shadows. Off by default: a shadowed key light reaches past geometry its
447
543
  /// shadow map ignores (single-sided back faces, the near plane around its fixture) and the lightmapper does not —
448
- /// 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.
449
545
  /// </summary>
450
546
  public bool bakeShadowedLights = false;
451
547
  /// <summary>Light names (or prefixes ending in *) that stay as they are.</summary>
@@ -470,12 +566,27 @@ public static class BtOptimize
470
566
  /// light. Off by default, because merging needs the newly lightmapped props.
471
567
  /// </summary>
472
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;
473
576
  /// <summary>Mark renderers static when nothing in the browser can move them.</summary>
474
577
  public bool markStatic = true;
475
578
  /// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
476
579
  public bool lightmapProbeLit = true;
477
580
  /// <summary>Deactivate motion blur overrides whose intensity is 0 in the profiles this scene uses (a no-op in Unity).</summary>
478
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;
479
590
  /// <summary>Object names (or prefixes ending in *) whose subtrees Tune never touches.</summary>
480
591
  public string[] exclude = new string[0];
481
592
  /// <summary>Plan only: report every change without making it (works on any scene, including the source).</summary>
@@ -510,10 +621,12 @@ public static class BtOptimize
510
621
  // The converted objects now have MeshRenderers: gather the scene again so the static and lightmap steps see them.
511
622
  if (converted > 0 && !options.dryRun) context = new Context(scene, sourceGIContributors);
512
623
  }
624
+ if (options.unfreezeAnimated) UnfreezeAnimated(context, options, changes, kept);
513
625
  if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
514
626
  if (options.markStatic) MarkStatic(context, options, changes, kept);
515
627
  if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
516
628
  if (options.instanceRepeatsFrom > 0) InstanceRepeats(context, options, changes, kept);
629
+ if (options.vatCrowdsFrom > 0) VatCrowds(context, options, changes, kept);
517
630
  if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
518
631
  // A dry run changed no flags, so its copy count is the one the planned changes would leave.
519
632
  int copyGIContributors = options.dryRun ? context.PlannedGIContributors.Count : GIContributorPaths(scene.GetRootGameObjects()).Count;
@@ -578,13 +691,15 @@ public static class BtOptimize
578
691
  if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "skinned", Path = path, Why = "--exclude" }); continue; }
579
692
  var verdict = ClassifySkinning(renderer, context);
580
693
  int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
581
- string copiesNote = copies > 1 ? " — " + copies + " copies" : "";
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" : "";
582
697
  if (!TuneConverts(verdict.Kind))
583
698
  {
584
699
  kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
585
700
  continue;
586
701
  }
587
- bool bakesPose = verdict.Kind == SkinRigidScriptHost || verdict.Kind == SkinFrozenPose;
702
+ bool bakesPose = bakesShape;
588
703
  string howPlaced;
589
704
  var mesh = bakesPose
590
705
  ? BakedPoseMesh(renderer, bakedFolder, bakedMeshes, !options.dryRun, out howPlaced)
@@ -600,6 +715,7 @@ public static class BtOptimize
600
715
  if (options.dryRun)
601
716
  {
602
717
  context.PlannedUnskinned.Add(renderer);
718
+ context.PlannedMeshKeys[renderer] = PlannedMeshKey(renderer, mesh, verdict, bakesPose, context);
603
719
  continue;
604
720
  }
605
721
  var gameObject = renderer.gameObject;
@@ -608,6 +724,7 @@ public static class BtOptimize
608
724
  }
609
725
  if (options.dryRun)
610
726
  {
727
+ RecountPlannedRepeats(context);
611
728
  DiscardUnsavedMeshes(bakedMeshes.Values);
612
729
  return converted;
613
730
  }
@@ -616,6 +733,24 @@ public static class BtOptimize
616
733
  return converted;
617
734
  }
618
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
+
619
754
  /// <summary>True for the skinning verdicts UnskinRigid converts to a plain mesh.</summary>
620
755
  private static bool TuneConverts(string verdictKind)
621
756
  {
@@ -766,7 +901,7 @@ public static class BtOptimize
766
901
  /// <summary>
767
902
  /// A light inside its own fixture (a lantern shell around the bulb) is lit fine in real time — the shadow map's near
768
903
  /// plane clips the shell — but the lightmapper traces from the bulb with no near plane, so a shadow-casting shell
769
- /// 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
770
905
  /// whose bounds hold the light stop casting shadows.
771
906
  /// </summary>
772
907
  private static void FreeFromFixture(Light light, TuneOptions options, List<Change> changes)
@@ -850,6 +985,7 @@ public static class BtOptimize
850
985
  {
851
986
  var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);
852
987
  if (!flags.HasFlag(StaticEditorFlags.BatchingStatic) && !flags.HasFlag(StaticEditorFlags.ContributeGI)) continue;
988
+ if (context.PlannedNonStatic.Contains(renderer.gameObject)) continue;
853
989
  var lod = renderer.GetComponentInParent<LODGroup>();
854
990
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
855
991
  if (level > 0) continue;
@@ -922,7 +1058,7 @@ public static class BtOptimize
922
1058
  changes.Add(new Change { Kind = "Light probes off (instancing)", Path = path,
923
1059
  Before = "Light Probes " + renderer.lightProbeUsage + ", Receive GI " + receive + (meshRenderer == null ? " (once unskinned)" : ""),
924
1060
  After = "Light Probes Off, Receive GI LightProbes, Reflection Probes " + renderer.reflectionProbeUsage,
925
- Why = context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
1061
+ Why = context.RepeatCounts[RepeatKeyOf(renderer, context)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
926
1062
  + " (SceneManager.DeinstanceProbeLitNodes); the copies light from the scene's ambient instead of the nearest probe" });
927
1063
  if (options.dryRun || meshRenderer == null) continue;
928
1064
  meshRenderer.lightProbeUsage = LightProbeUsage.Off;
@@ -931,6 +1067,274 @@ public static class BtOptimize
931
1067
  }
932
1068
  }
933
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
+
934
1338
  /// <summary>
935
1339
  /// True when --keep-gi forbids Contribute GI on the object at this hierarchy path: it did not contribute GI in the
936
1340
  /// source scene, and adding it would pull the object into the re-bake (darkening the source's indirect light).
@@ -1002,27 +1406,401 @@ public static class BtOptimize
1002
1406
  }
1003
1407
  }
1004
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 lightmapped renderer
1518
+ /// whose lightmap index names a lightmap the bake does not have (an empty or stale LightingData); a camera whose enabled
1519
+ /// state differs from the source (a capture step that disabled the main camera and was saved ships a game with no
1520
+ /// post-processing); lighting settings that differ from the source; rigid skinned meshes Tune converts that are
1521
+ /// still skinned; repeated meshes (instanceRepeatsFrom copies or more) that are lightmapped or probe-lit; static
1522
+ /// objects that move in the browser; VAT crowd members missing their materials, unit scale or probes-off; pruned
1523
+ /// shadow casters casting again; with keepSourceGI, GI contributors the source does not have. Changes nothing.
1524
+ /// </summary>
1525
+ /// <param name="optionsJson">The TuneOptions the copy was tuned with (thresholds and exclusions), or empty for the defaults.</param>
1526
+ /// <returns>"problems=N" and one line per problem.</returns>
1527
+ public static string Verify(string optionsJson)
1528
+ {
1529
+ var options = string.IsNullOrWhiteSpace(optionsJson) ? new TuneOptions() : JsonUtility.FromJson<TuneOptions>(optionsJson);
1530
+ var scene = SceneManager.GetActiveScene();
1531
+ string folder = ReportFolder(scene);
1532
+ string recordPath = Path.Combine(folder, "working-copy.txt");
1533
+ if (!File.Exists(recordPath)) throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy (no " + recordPath + ").");
1534
+ string sourcePath = File.ReadAllText(recordPath).Trim();
1535
+ var context = new Context(scene);
1536
+ var problems = new List<string>();
1537
+ var checks = new Dictionary<string, object>();
1538
+
1539
+ if (scene.isDirty) problems.Add("the scene has unsaved changes — save it before exporting");
1540
+ if (FindPoseCameras().Any(camera => camera.gameObject.scene == scene)) problems.Add(PoseCameraName + " is in the scene — reopen the scene before exporting (it would export as a camera)");
1541
+
1542
+ // Read before the source is opened additively: loading it merges its lightmaps into LightmapSettings.
1543
+ var badLightmapIndices = LightmapIndexOutOfRange(scene);
1544
+ problems.AddRange(badLightmapIndices.Select(entry => "lightmapped renderer points past the baked lightmaps — re-bake: " + entry));
1545
+ checks["lightmaps"] = new Dictionary<string, object> { { "baked", LightmapSettings.lightmaps.Length }, { "indexOutOfRange", badLightmapIndices.Count } };
1546
+
1547
+ var copyCameras = CameraStates(scene);
1548
+ var copyLighting = ReadLighting(scene);
1549
+ var source = ReadFromScene(sourcePath, scene, sourceScene => new { cameras = CameraStates(sourceScene), lighting = ReadLighting(sourceScene), contributors = GIContributorPaths(sourceScene.GetRootGameObjects()) });
1550
+ foreach (var camera in source.cameras)
1551
+ {
1552
+ if (!copyCameras.TryGetValue(camera.Key, out bool enabled)) problems.Add("camera " + camera.Key + " is missing from the copy");
1553
+ 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");
1554
+ }
1555
+ foreach (var setting in source.lighting.Where(setting => !copyLighting.TryGetValue(setting.Key, out var value) || value != setting.Value))
1556
+ problems.Add("lighting " + setting.Key + ": copy " + (copyLighting.TryGetValue(setting.Key, out var copyValue) ? copyValue : "missing") + ", source " + setting.Value);
1557
+ checks["lighting"] = copyLighting.ToDictionary(pair => pair.Key, pair => (object)pair.Value);
1558
+
1559
+ var rigidLeft = context.Renderers.OfType<SkinnedMeshRenderer>().Where(renderer => !IsExcluded(renderer.transform, options.exclude))
1560
+ .Where(renderer => options.unskinRigid && TuneConverts(ClassifySkinning(renderer, context).Kind)).Select(renderer => PathOf(renderer.transform)).ToList();
1561
+ problems.AddRange(rigidLeft.Select(path => "still skinned although it needs no skinning: " + path));
1562
+ checks["rigidSkinnedLeft"] = rigidLeft.Count;
1563
+ checks["skinnedLeft"] = context.Renderers.OfType<SkinnedMeshRenderer>().Count();
1564
+
1565
+ var repeats = options.instanceRepeatsFrom <= 0 ? new List<Renderer>() : context.Renderers.OfType<MeshRenderer>().Cast<Renderer>()
1566
+ .Where(renderer => !IsExcluded(renderer.transform, options.exclude) && IsRepeatedForInstancing(renderer, context, options)).ToList();
1567
+ var lightmappedRepeats = repeats.Where(renderer => ((MeshRenderer)renderer).receiveGI == ReceiveGI.Lightmaps
1568
+ && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI)).Select(renderer => PathOf(renderer.transform)).ToList();
1569
+ var probeLitRepeats = repeats.Where(renderer => renderer.lightProbeUsage != LightProbeUsage.Off).Select(renderer => PathOf(renderer.transform)).Except(lightmappedRepeats).ToList();
1570
+ problems.AddRange(lightmappedRepeats.Select(path => "repeated mesh is lightmapped (its copies cannot instance): " + path));
1571
+ problems.AddRange(probeLitRepeats.Select(path => "repeated mesh is probe-lit (the toolkit de-instances it): " + path));
1572
+ checks["repeatRenderers"] = repeats.Count;
1573
+
1574
+ if (options.unfreezeAnimated)
1575
+ {
1576
+ var staticMovers = context.Roots.SelectMany(root => root.GetComponentsInChildren<Transform>(true))
1577
+ .Where(transform => GameObjectUtility.GetStaticEditorFlags(transform.gameObject) != 0 && !IsExcluded(transform, options.exclude))
1578
+ .Select(transform => new { transform, mover = BrowserMoverOf(transform, context) }).Where(entry => entry.mover != null)
1579
+ .Select(entry => PathOf(entry.transform) + " (" + entry.mover + ")").ToList();
1580
+ problems.AddRange(staticMovers.Select(entry => "static but moves in the browser: " + entry));
1581
+ checks["staticMovers"] = staticMovers.Count;
1582
+ }
1583
+
1584
+ var rigType = AnimatorControlRigType();
1585
+ var vatAnimators = rigType == null ? new List<Animator>() : context.All<Animator>().Where(animator => IsVertexAnimated(animator, rigType)).ToList();
1586
+ foreach (var animator in vatAnimators)
1587
+ foreach (var skinned in animator.GetComponentsInChildren<SkinnedMeshRenderer>(true).Where(skinned => skinned.GetComponentInParent<Animator>() == animator))
1588
+ {
1589
+ string path = PathOf(skinned.transform);
1590
+ if (skinned.sharedMaterials.Any(material => material == null || material.shader.name != VertexAnimationShaderName)) problems.Add("VAT crowd member has a material not on " + VertexAnimationShaderName + ": " + path);
1591
+ 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);
1592
+ if (skinned.lightProbeUsage != LightProbeUsage.Off) problems.Add("VAT crowd member is probe-lit (its copies would not instance): " + path);
1593
+ }
1594
+ checks["vatCrowdMembers"] = vatAnimators.Count;
1595
+
1596
+ string prunedPath = Path.Combine(folder, PrunedCastersFileName);
1597
+ if (File.Exists(prunedPath))
1598
+ {
1599
+ var record = ReadPrunedCasters(prunedPath);
1600
+ foreach (string path in record.paths)
1601
+ {
1602
+ var renderer = context.Renderers.FirstOrDefault(candidate => PathOf(candidate.transform) == path);
1603
+ if (renderer == null) problems.Add("pruned shadow caster is missing: " + path);
1604
+ else if (renderer.shadowCastingMode != ShadowCastingMode.Off) problems.Add("pruned shadow caster casts again: " + path);
1605
+ }
1606
+ checks["prunedCasters"] = record.paths.Length;
1607
+ }
1608
+
1609
+ var copyContributors = GIContributorPaths(scene.GetRootGameObjects());
1610
+ var newContributors = copyContributors.Except(source.contributors).ToList();
1611
+ if (options.keepSourceGI) problems.AddRange(newContributors.Select(path => "--keep-gi: contributes GI but did not in the source: " + path));
1612
+ checks["giContributors"] = new Dictionary<string, object> { { "source", source.contributors.Count }, { "copy", copyContributors.Count }, { "new", newContributors.Count } };
1613
+
1614
+ var md = new StringBuilder("# bt-optimize verify — " + scene.path + "\n\nSource: `" + sourcePath + "`\n\n**Problems: " + problems.Count + "**\n\n");
1615
+ foreach (var problem in problems) md.AppendLine("- " + problem);
1616
+ md.AppendLine("\n## Checks\n");
1617
+ 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));
1618
+ File.WriteAllText(Path.Combine(folder, "verify.md"), md.ToString());
1619
+ File.WriteAllText(Path.Combine(folder, "verify.json"), ToJson(new Dictionary<string, object> { { "scene", scene.path }, { "source", sourcePath },
1620
+ { "problems", problems.Cast<object>().ToList() }, { "checks", checks } }, 0));
1621
+ return "problems=" + problems.Count + "\n" + string.Join("\n", problems.Take(40)) + (problems.Count > 40 ? "\n… (all in verify.md)" : "");
1622
+ }
1623
+
1624
+ /// <summary>
1625
+ /// Reads something from another scene: an open one is read as it is; otherwise it is opened additively, made the
1626
+ /// active scene while it is read (RenderSettings and lighting settings belong to the active scene), and closed unsaved.
1627
+ /// </summary>
1628
+ private static T ReadFromScene<T>(string scenePath, Scene returnTo, Func<Scene, T> read)
1629
+ {
1630
+ var open = SceneManager.GetSceneByPath(scenePath);
1631
+ bool opened = !open.isLoaded;
1632
+ var scene = opened ? EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive) : open;
1633
+ try
1634
+ {
1635
+ SceneManager.SetActiveScene(scene);
1636
+ return read(scene);
1637
+ }
1638
+ finally
1639
+ {
1640
+ SceneManager.SetActiveScene(returnTo);
1641
+ if (opened) EditorSceneManager.CloseScene(scene, true);
1642
+ }
1643
+ }
1644
+
1645
+ /// <summary>Every camera's hierarchy path and whether it renders (enabled on an active object).</summary>
1646
+ private static Dictionary<string, bool> CameraStates(Scene scene)
1647
+ {
1648
+ var states = new Dictionary<string, bool>();
1649
+ foreach (var camera in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(camera => !IsPoseCamera(camera)))
1650
+ states[PathOf(camera.transform)] = camera.enabled && camera.gameObject.activeInHierarchy;
1651
+ return states;
1652
+ }
1653
+
1654
+ /// <summary>Unity's lightmap index for "not lightmapped, but contributes to GI" (static objects baked into probes only).</summary>
1655
+ private const int LightmapIndexNotLightmappedGI = 0xFFFE;
1656
+
1657
+ /// <summary>
1658
+ /// Every renderer and terrain in the scene whose lightmap index names a lightmap the loaded bake does not have — a
1659
+ /// LightingData that is empty, stale or from another scene. Each entry is "path index=N of M". The scene must be the
1660
+ /// only loaded scene with lightmaps (an additive scene's lightmaps shift the indices).
1661
+ /// </summary>
1662
+ private static List<string> LightmapIndexOutOfRange(Scene scene)
1663
+ {
1664
+ int lightmapCount = LightmapSettings.lightmaps.Length;
1665
+ bool OutOfRange(int index) => index >= 0 && index < LightmapIndexNotLightmappedGI && index >= lightmapCount;
1666
+ var roots = scene.GetRootGameObjects();
1667
+ var renderers = roots.SelectMany(root => root.GetComponentsInChildren<Renderer>(true))
1668
+ .Where(renderer => OutOfRange(renderer.lightmapIndex)).Select(renderer => PathOf(renderer.transform) + " index=" + renderer.lightmapIndex + " of " + lightmapCount);
1669
+ var terrains = roots.SelectMany(root => root.GetComponentsInChildren<Terrain>(true))
1670
+ .Where(terrain => OutOfRange(terrain.lightmapIndex)).Select(terrain => PathOf(terrain.transform) + " index=" + terrain.lightmapIndex + " of " + lightmapCount);
1671
+ return renderers.Concat(terrains).ToList();
1672
+ }
1673
+
1674
+ /// <summary>
1675
+ /// The scene's lighting setup as text, for comparing a copy with its source: the Lighting Settings (mixed mode,
1676
+ /// indirect intensity, albedo boost, lightmapper, resolution), ambient and reflection settings, skybox, fog, and the
1677
+ /// main directional light's mode and shadows. The scene must be the active scene.
1678
+ /// </summary>
1679
+ private static Dictionary<string, string> ReadLighting(Scene scene)
1680
+ {
1681
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
1682
+ var values = new Dictionary<string, string>();
1683
+ LightingSettings settings = null;
1684
+ try { settings = Lightmapping.lightingSettings; } catch (Exception) { /* the scene has no Lighting Settings asset */ }
1685
+ if (settings != null)
1686
+ {
1687
+ values["mixedBakeMode"] = settings.mixedBakeMode.ToString();
1688
+ values["indirectScale"] = settings.indirectScale.ToString("0.###", culture);
1689
+ values["albedoBoost"] = settings.albedoBoost.ToString("0.###", culture);
1690
+ values["lightmapper"] = settings.lightmapper.ToString();
1691
+ values["lightmapResolution"] = settings.lightmapResolution.ToString("0.###", culture);
1692
+ }
1693
+ values["ambientMode"] = RenderSettings.ambientMode.ToString();
1694
+ values["ambientColor"] = RenderSettings.ambientLight.ToString("F3");
1695
+ values["ambientIntensity"] = RenderSettings.ambientIntensity.ToString("0.###", culture);
1696
+ values["reflectionIntensity"] = RenderSettings.reflectionIntensity.ToString("0.###", culture);
1697
+ values["skybox"] = RenderSettings.skybox != null ? RenderSettings.skybox.name : "none";
1698
+ values["fog"] = RenderSettings.fog + " " + RenderSettings.fogMode + " " + RenderSettings.fogColor.ToString("F3");
1699
+ var sun = RenderSettings.sun != null && RenderSettings.sun.gameObject.scene == scene ? RenderSettings.sun
1700
+ : scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Light>(true))
1701
+ .Where(light => light.isActiveAndEnabled && light.type == LightType.Directional).OrderByDescending(light => light.intensity).FirstOrDefault();
1702
+ values["sun"] = sun != null ? sun.name + " " + sun.lightmapBakeType + " shadows " + sun.shadows + " intensity " + sun.intensity.ToString("0.###", culture) : "none";
1703
+ return values;
1704
+ }
1705
+
1706
+ /// <summary>A bake that has not written its LightingData this many seconds after it was started, and is not running, has stopped.</summary>
1707
+ private const long BakeStartGraceSeconds = 120;
1708
+
1709
+ /// <summary>
1710
+ /// Where a bake started at the given time stands, for `wait.mjs cmd` to poll: "baking" while the lightmapper runs;
1711
+ /// once it has stopped and the active scene's LightingData asset was written at or after the start, "done" — or
1712
+ /// "empty" when that bake wrote no lightmaps although the scene has lightmapped renderers, or no light probes although
1713
+ /// it has a LightProbeGroup (a failed bake still writes its LightingData, so the write time alone proves nothing);
1714
+ /// "stopped" when it is not running and wrote nothing more than BakeStartGraceSeconds after the start; "waiting"
1715
+ /// otherwise. "done" and "empty" are followed by the counts (`done lightmaps=12 probes=2400 lightmapped=380
1716
+ /// probeGroups=1 data=Assets/…/LightingData.asset`). `lighting_bake_status` alone can report "completed" before the
1717
+ /// bake has started.
1718
+ /// </summary>
1719
+ /// <param name="startedUnixSeconds">When bake_lighting was called, in Unix seconds (`date +%s`).</param>
1720
+ public static string BakeState(string startedUnixSeconds)
1721
+ {
1722
+ long started = long.Parse(startedUnixSeconds, System.Globalization.CultureInfo.InvariantCulture);
1723
+ if (Lightmapping.isRunning) return "baking";
1724
+ var data = Lightmapping.lightingDataAsset;
1725
+ string path = data != null ? AssetDatabase.GetAssetPath(data) : "";
1726
+ long written = path.Length > 0 && File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path)).ToUnixTimeSeconds() : 0;
1727
+ if (written < started) return DateTimeOffset.UtcNow.ToUnixTimeSeconds() - started > BakeStartGraceSeconds ? "stopped" : "waiting";
1728
+
1729
+ var scene = SceneManager.GetActiveScene();
1730
+ int lightmaps = LightmapSettings.lightmaps.Length;
1731
+ int probes = LightmapSettings.lightProbes != null ? LightmapSettings.lightProbes.count : 0;
1732
+ int lightmapped = CountLightmappedRenderers(scene);
1733
+ int probeGroups = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<LightProbeGroup>(false))
1734
+ .Count(group => group.enabled && group.probePositions.Length > 0);
1735
+ bool empty = (lightmapped > 0 && lightmaps == 0) || (probeGroups > 0 && probes == 0);
1736
+ return (empty ? "empty" : "done") + " lightmaps=" + lightmaps + " probes=" + probes + " lightmapped=" + lightmapped
1737
+ + " probeGroups=" + probeGroups + " data=" + (path.Length > 0 ? path : "none");
1738
+ }
1739
+
1740
+ /// <summary>
1741
+ /// How many active renderers and terrains in the scene the lightmapper bakes into lightmaps: Contribute GI static,
1742
+ /// and (for mesh renderers) Receive GI set to Lightmaps.
1743
+ /// </summary>
1744
+ private static int CountLightmappedRenderers(Scene scene)
1745
+ {
1746
+ var roots = scene.GetRootGameObjects();
1747
+ bool ContributesGI(GameObject gameObject) => GameObjectUtility.GetStaticEditorFlags(gameObject).HasFlag(StaticEditorFlags.ContributeGI);
1748
+ int meshRenderers = roots.SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(false))
1749
+ .Count(renderer => renderer.enabled && renderer.receiveGI == ReceiveGI.Lightmaps && ContributesGI(renderer.gameObject));
1750
+ int terrains = roots.SelectMany(root => root.GetComponentsInChildren<Terrain>(false)).Count(terrain => terrain.enabled && ContributesGI(terrain.gameObject));
1751
+ return meshRenderers + terrains;
1752
+ }
1753
+
1754
+ /// <summary>The name of the capture camera PoseView places.</summary>
1755
+ private const string PoseCameraName = "BtOptimizePoseCamera";
1756
+
1757
+ /// <summary>
1758
+ /// Whether a camera is a PoseView capture camera: named PoseCameraName and living in the Editor, not an asset (a
1759
+ /// prefab that happens to use the name is never touched).
1760
+ /// </summary>
1761
+ private static bool IsPoseCamera(Camera camera) => camera != null && camera.name == PoseCameraName && !EditorUtility.IsPersistent(camera);
1762
+
1763
+ /// <summary>
1764
+ /// Every PoseView capture camera the Editor holds — in the active scene, in another loaded scene, or orphaned outside
1765
+ /// any scene. The camera is DontSaveInEditor, and such an object survives OpenScene(Single), so a lookup through the
1766
+ /// active scene's roots alone misses the one left by an earlier scene.
1767
+ /// </summary>
1768
+ private static List<Camera> FindPoseCameras() => Resources.FindObjectsOfTypeAll<Camera>().Where(IsPoseCamera).ToList();
1769
+
1770
+ /// <summary>Destroys every PoseView capture camera (see FindPoseCameras), so the next capture renders through exactly one.</summary>
1771
+ /// <returns>How many were destroyed.</returns>
1772
+ private static int DestroyPoseCameras()
1773
+ {
1774
+ var cameras = FindPoseCameras();
1775
+ foreach (var camera in cameras) UnityEngine.Object.DestroyImmediate(camera.gameObject);
1776
+ return cameras.Count;
1777
+ }
1778
+
1005
1779
  /// <summary>
1006
1780
  /// Opens the scene (discarding nothing: refuses when the open scene has unsaved changes) and places a capture camera
1007
1781
  /// named "BtOptimizePoseCamera" at a pose recorded by the browser profiler (toolkit scenes keep Unity's coordinates),
1008
1782
  /// copying the main camera's settings and URP data so post-processing matches. Capture it with
1009
- /// `capture_game_view --camera BtOptimizePoseCamera`. The camera is never saved: reopening the scene removes it.
1783
+ /// `capture_game_view --camera BtOptimizePoseCamera`. It never touches the scene's own cameras (a disabled main camera
1784
+ /// that got saved once shipped a game with no post-processing): the pose camera renders above them by depth and is
1785
+ /// flagged DontSaveInEditor, so it is never written to the scene. Reopen the scene before exporting — the exporter
1786
+ /// would otherwise see it as one more camera. Every earlier pose camera is destroyed first, wherever it is (one left
1787
+ /// by another scene survives OpenScene), so exactly one renders the capture.
1010
1788
  /// </summary>
1011
1789
  public static string PoseView(string scenePath, float px, float py, float pz, float qx, float qy, float qz, float qw, float verticalFovRadians)
1012
1790
  {
1013
1791
  var active = SceneManager.GetActiveScene();
1792
+ // The only unsaved change PoseView allows itself to discard is its own pose camera.
1793
+ bool onlyPoseCamera = FindPoseCameras().Any(camera => camera.gameObject.scene == active);
1794
+ DestroyPoseCameras();
1014
1795
  if (active.path != scenePath)
1015
1796
  {
1016
- // The only unsaved change PoseView allows itself to discard is its own pose camera.
1017
- bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == "BtOptimizePoseCamera");
1018
1797
  if (active.isDirty && !onlyPoseCamera) throw new InvalidOperationException("'" + active.path + "' has unsaved changes; save or discard them first.");
1019
1798
  EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
1799
+ DestroyPoseCameras();
1020
1800
  }
1021
1801
  var scene = SceneManager.GetActiveScene();
1022
- var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == "BtOptimizePoseCamera");
1023
- if (existing != null) UnityEngine.Object.DestroyImmediate(existing);
1024
1802
  var main = Camera.main;
1025
- var go = new GameObject("BtOptimizePoseCamera");
1803
+ var go = new GameObject(PoseCameraName) { hideFlags = HideFlags.DontSaveInEditor };
1026
1804
  var camera = go.AddComponent<Camera>();
1027
1805
  if (main != null)
1028
1806
  {
@@ -1033,8 +1811,11 @@ public static class BtOptimize
1033
1811
  var data = go.GetComponent(mainData.GetType()) ?? go.AddComponent(mainData.GetType());
1034
1812
  EditorUtility.CopySerialized(mainData, data);
1035
1813
  }
1036
- main.enabled = false;
1037
1814
  }
1815
+ // Render above every scene camera instead of disabling any of them: the scene's cameras are never changed.
1816
+ var sceneCameras = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(other => !IsPoseCamera(other)).ToList();
1817
+ camera.depth = sceneCameras.Count > 0 ? sceneCameras.Max(other => other.depth) + 1f : camera.depth;
1818
+ foreach (var component in go.GetComponents<Component>()) component.hideFlags = HideFlags.DontSaveInEditor;
1038
1819
  go.transform.SetPositionAndRotation(new Vector3(px, py, pz), new Quaternion(qx, qy, qz, qw));
1039
1820
  camera.fieldOfView = verticalFovRadians * Mathf.Rad2Deg;
1040
1821
  camera.enabled = true;
@@ -1126,8 +1907,8 @@ public static class BtOptimize
1126
1907
  /// <summary>
1127
1908
  /// Why the renderer is not a visible, lightmappable surface, or null. Only shaders with a lightmapper Meta pass
1128
1909
  /// (URP Lit / Simple Lit / Unlit, Built-in Standard, Shader Graph Lit / Unlit…) describe a surface to the bake.
1129
- /// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, Garden's invisible
1130
- /// `Room1Screens` stencil mesh (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
1910
+ /// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, an invisible stencil mesh
1911
+ /// (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
1131
1912
  /// room went dark.
1132
1913
  /// </summary>
1133
1914
  private static string NotAVisibleSurface(Renderer renderer)
@@ -1355,8 +2136,7 @@ public static class BtOptimize
1355
2136
  /// </summary>
1356
2137
  private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
1357
2138
  {
1358
- string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1359
- string cacheKey = source.GetHashCode() + "|" + offsetKey;
2139
+ string cacheKey = source.GetHashCode() + "|" + OffsetKey(meshToObject);
1360
2140
  if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
1361
2141
  var baked = UnityEngine.Object.Instantiate(source);
1362
2142
  baked.name = source.name + "_Unskinned_" + bakedMeshes.Count;
@@ -1381,6 +2161,12 @@ public static class BtOptimize
1381
2161
  return baked;
1382
2162
  }
1383
2163
 
2164
+ /// <summary>A bind-pose offset matrix as text, rounded to SharedMeshKeyDecimals: copies with equal keys share one baked mesh.</summary>
2165
+ private static string OffsetKey(Matrix4x4 meshToObject)
2166
+ {
2167
+ return string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
2168
+ }
2169
+
1384
2170
  /// <summary>
1385
2171
  /// Folder for meshes baked from skinned meshes (offset rigid meshes and baked poses): &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1386
2172
  /// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
@@ -1704,7 +2490,17 @@ public static class BtOptimize
1704
2490
  /// <summary>True when the renderer's mesh and materials repeat often enough that its copies should share an instanced draw.</summary>
1705
2491
  private static bool IsRepeatedForInstancing(Renderer renderer, Context context, TuneOptions options)
1706
2492
  {
1707
- return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) && copies >= options.instanceRepeatsFrom;
2493
+ return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKeyOf(renderer, context), out var copies) && copies >= options.instanceRepeatsFrom;
2494
+ }
2495
+
2496
+ /// <summary>
2497
+ /// RepeatKey, except that a skinned renderer a dry run plans to convert is keyed by the mesh it will draw
2498
+ /// (see PlannedMeshKey) rather than the skinned mesh it draws now.
2499
+ /// </summary>
2500
+ private static string RepeatKeyOf(Renderer renderer, Context context)
2501
+ {
2502
+ if (!(renderer is SkinnedMeshRenderer skinned) || !context.PlannedMeshKeys.TryGetValue(skinned, out var plannedMesh)) return RepeatKey(renderer);
2503
+ return "planned " + plannedMesh + "|" + string.Join(",", renderer.sharedMaterials.Select(material => material != null ? material.GetHashCode() : 0));
1708
2504
  }
1709
2505
 
1710
2506
  /// <summary>
@@ -1774,6 +2570,10 @@ public static class BtOptimize
1774
2570
  public readonly HashSet<string> PlannedGIContributors;
1775
2571
  /// <summary>Skinned renderers a dry run plans to convert: later steps treat them as the MeshRenderers they become.</summary>
1776
2572
  public readonly List<SkinnedMeshRenderer> PlannedUnskinned = new List<SkinnedMeshRenderer>();
2573
+ /// <summary>For each renderer a dry run plans to convert, the identity of the mesh it will draw (see PlannedMeshKey).</summary>
2574
+ public readonly Dictionary<SkinnedMeshRenderer, string> PlannedMeshKeys = new Dictionary<SkinnedMeshRenderer, string>();
2575
+ /// <summary>Objects whose static flags Tune clears (UnfreezeAnimated); a dry run's later steps treat them as non-static.</summary>
2576
+ public readonly HashSet<GameObject> PlannedNonStatic = new HashSet<GameObject>();
1777
2577
  public readonly StringBuilder Summary = new StringBuilder();
1778
2578
 
1779
2579
  /// <param name="scene">The scene to gather.</param>