diff --git a/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs b/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs new file mode 100644 index 0000000..898d124 --- /dev/null +++ b/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace ZoneUA.EditorValidation +{ + public enum CompositionMigrationStatus { Missing, Added, Error } + + [Serializable] + public sealed class CompositionMigrationIssue + { + public CompositionMigrationStatus status; + public string assetPath; + public string hierarchyPath; + public string message; + } + + [Serializable] + public sealed class CompositionMigrationReport + { + public readonly List Issues = new List(); + public int MissingCount => Issues.Count(issue => issue.status == CompositionMigrationStatus.Missing); + public int AddedCount => Issues.Count(issue => issue.status == CompositionMigrationStatus.Added); + public int ErrorCount => Issues.Count(issue => issue.status == CompositionMigrationStatus.Error); + public bool IsClean => MissingCount == 0 && ErrorCount == 0; + + public void Add(CompositionMigrationStatus status, string assetPath, string hierarchyPath, string message) + { + Issues.Add(new CompositionMigrationIssue + { + status = status, + assetPath = assetPath ?? string.Empty, + hierarchyPath = hierarchyPath ?? string.Empty, + message = message ?? string.Empty + }); + } + } + + public sealed class CompositionMigrationWindow : EditorWindow + { + private CompositionMigrationReport report; + private Vector2 scroll; + + public static void ShowReport(CompositionMigrationReport report) + { + CompositionMigrationWindow window = GetWindow("Composition Migration"); + window.report = report; + window.Show(); + } + + private void OnGUI() + { + if (report == null) + { + EditorGUILayout.HelpBox("Run a Zone UA migration or audit command.", MessageType.Info); + return; + } + + EditorGUILayout.LabelField("Production composition", EditorStyles.boldLabel); + EditorGUILayout.LabelField($"Missing: {report.MissingCount} Added: {report.AddedCount} Errors: {report.ErrorCount}"); + scroll = EditorGUILayout.BeginScrollView(scroll); + foreach (CompositionMigrationIssue issue in report.Issues) + { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + EditorGUILayout.LabelField(issue.status.ToString(), EditorStyles.boldLabel); + EditorGUILayout.LabelField(issue.message, EditorStyles.wordWrappedLabel); + EditorGUILayout.LabelField(issue.assetPath, EditorStyles.miniLabel); + if (!string.IsNullOrEmpty(issue.hierarchyPath)) + EditorGUILayout.LabelField(issue.hierarchyPath, EditorStyles.miniLabel); + if (GUILayout.Button("Select asset")) + { + UnityEngine.Object asset = AssetDatabase.LoadMainAssetAtPath(issue.assetPath); + Selection.activeObject = asset; + EditorGUIUtility.PingObject(asset); + } + EditorGUILayout.EndVertical(); + } + EditorGUILayout.EndScrollView(); + } + } +} diff --git a/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs.meta b/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs.meta new file mode 100644 index 0000000..ef5922a --- /dev/null +++ b/Assets/_ZoneUA/Editor/CompositionMigrationReport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6820d111eb9b478aaf3f972f5adb857f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs b/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs new file mode 100644 index 0000000..190f204 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; + +namespace ZoneUA.EditorValidation +{ + [Serializable] + public sealed class ProductionCompositionRule + { + public string Name { get; } + public string AnchorTypeName { get; } + public bool CanAutoAdd { get; } + public IReadOnlyList RequiredTypeNames { get; } + + public ProductionCompositionRule( + string name, + string anchorTypeName, + bool canAutoAdd, + params string[] requiredTypeNames) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + AnchorTypeName = anchorTypeName ?? throw new ArgumentNullException(nameof(anchorTypeName)); + CanAutoAdd = canAutoAdd; + RequiredTypeNames = requiredTypeNames ?? Array.Empty(); + } + } + + public static class ProductionCompositionCatalog + { + private static readonly ProductionCompositionRule[] RulesInternal = + { + new ProductionCompositionRule( + "Player root", + "CharacterCustomController", + true, + "Health", + "Death", + "PlayerInputRouter", + "WeaponSwitcher"), + new ProductionCompositionRule( + "NPC actor", + "NPCController", + true, + "Health", + "Death", + "ZoneUA.Factions.FactionMember"), + new ProductionCompositionRule( + "Weapon", + "WeaponController", + true, + "Weapon", + "ZoneUA.Combat.ProjectileSpawner", + "ZoneUA.Combat.ShellEjector", + "ZoneUA.Combat.WeaponAudio", + "ZoneUA.Combat.WeaponRecoil"), + new ProductionCompositionRule( + "Damage presentation", + "Health", + false, + "DamageEffectsPresenter"), + new ProductionCompositionRule( + "World root", + "MapGenerator", + true, + "ChunkManager"), + new ProductionCompositionRule( + "Ammo HUD", + "UIAmmoSystem", + false, + "WeaponAmmoPresenter") + }; + + public static IReadOnlyList Rules => RulesInternal; + } +} diff --git a/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs.meta b/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs.meta new file mode 100644 index 0000000..f7af61f --- /dev/null +++ b/Assets/_ZoneUA/Editor/ProductionCompositionRule.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b21a7d4ec8d4e05a0e0af93593fcfe2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs b/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs new file mode 100644 index 0000000..4837e52 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace ZoneUA.EditorValidation +{ + public static class ZoneUAProductionMigrator + { + [MenuItem("Zone UA/Migration/Audit Production Composition", priority = 20)] + public static void AuditProject() => + CompositionMigrationWindow.ShowReport(AuditAssets(FindProductionAssetPaths(), false)); + + [MenuItem("Zone UA/Migration/Migrate Selected Prefabs", priority = 21)] + public static void MigrateSelectedPrefabs() + { + string[] paths = Selection.objects + .Select(AssetDatabase.GetAssetPath) + .Where(path => path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) + .Distinct() + .ToArray(); + + CompositionMigrationReport report = AuditAssets(paths, true); + AssetDatabase.SaveAssets(); + CompositionMigrationWindow.ShowReport(report); + } + + [MenuItem("Zone UA/Migration/Migrate All Production Prefabs", priority = 22)] + public static void MigrateAllProductionPrefabs() + { + if (!EditorUtility.DisplayDialog( + "Migrate production prefabs", + "Safe missing composition components will be added to first-party prefabs. Existing GUIDs, components and prefab references are preserved.", + "Migrate", + "Cancel")) + { + return; + } + + CompositionMigrationReport report = AuditAssets(FindProductionAssetPaths(), true); + AssetDatabase.SaveAssets(); + CompositionMigrationWindow.ShowReport(report); + } + + [MenuItem("Zone UA/Migration/Audit Open Scenes", priority = 23)] + public static void AuditOpenScenes() => + CompositionMigrationWindow.ShowReport(ProcessOpenScenes(false)); + + [MenuItem("Zone UA/Migration/Migrate Open Scenes", priority = 24)] + public static void MigrateOpenScenes() => + CompositionMigrationWindow.ShowReport(ProcessOpenScenes(true)); + + public static CompositionMigrationReport AuditAssets(IEnumerable assetPaths, bool applyFixes) + { + var report = new CompositionMigrationReport(); + foreach (string path in assetPaths.Where(path => !string.IsNullOrWhiteSpace(path)).Distinct()) + { + if (path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) + { + AuditPrefab(path, applyFixes, report); + } + } + + return report; + } + + private static CompositionMigrationReport ProcessOpenScenes(bool applyFixes) + { + var report = new CompositionMigrationReport(); + for (int i = 0; i < SceneManager.sceneCount; i++) + { + Scene scene = SceneManager.GetSceneAt(i); + if (!scene.isLoaded) continue; + + bool changed = false; + foreach (GameObject root in scene.GetRootGameObjects()) + { + changed |= AuditHierarchy(root, scene.path, applyFixes, report); + } + + if (changed && applyFixes) + { + EditorSceneManager.MarkSceneDirty(scene); + } + } + + return report; + } + + private static void AuditPrefab(string path, bool applyFixes, CompositionMigrationReport report) + { + GameObject root = null; + try + { + root = PrefabUtility.LoadPrefabContents(path); + if (root == null) + { + report.Add(CompositionMigrationStatus.Error, path, string.Empty, "Prefab contents could not be loaded."); + return; + } + + bool changed = AuditHierarchy(root, path, applyFixes, report); + if (changed && applyFixes) + { + PrefabUtility.SaveAsPrefabAsset(root, path); + } + } + catch (Exception exception) + { + report.Add(CompositionMigrationStatus.Error, path, string.Empty, exception.Message); + } + finally + { + if (root != null) + { + PrefabUtility.UnloadPrefabContents(root); + } + } + } + + private static bool AuditHierarchy( + GameObject root, + string assetPath, + bool applyFixes, + CompositionMigrationReport report) + { + bool changed = false; + foreach (Transform target in root.GetComponentsInChildren(true)) + { + foreach (ProductionCompositionRule rule in ProductionCompositionCatalog.Rules) + { + Type anchorType = RuntimeTypeResolver.Resolve(rule.AnchorTypeName); + if (anchorType == null || target.GetComponent(anchorType) == null) continue; + + foreach (string requiredTypeName in rule.RequiredTypeNames) + { + Type requiredType = RuntimeTypeResolver.Resolve(requiredTypeName); + string hierarchyPath = GetHierarchyPath(target); + + if (requiredType == null) + { + report.Add( + CompositionMigrationStatus.Error, + assetPath, + hierarchyPath, + $"Required type '{requiredTypeName}' could not be resolved for '{rule.Name}'."); + continue; + } + + if (!typeof(Component).IsAssignableFrom(requiredType)) + { + report.Add( + CompositionMigrationStatus.Error, + assetPath, + hierarchyPath, + $"Required type '{requiredType.FullName}' is not a Component."); + continue; + } + + if (target.GetComponent(requiredType) != null) continue; + + if (!applyFixes || !rule.CanAutoAdd) + { + string suffix = rule.CanAutoAdd ? string.Empty : " Manual reference wiring is required."; + report.Add( + CompositionMigrationStatus.Missing, + assetPath, + hierarchyPath, + $"Missing {requiredType.Name} required by '{rule.Name}'.{suffix}"); + continue; + } + + Undo.AddComponent(target.gameObject, requiredType); + changed = true; + report.Add( + CompositionMigrationStatus.Added, + assetPath, + hierarchyPath, + $"Added {requiredType.Name} for '{rule.Name}'."); + } + } + } + + return changed; + } + + private static IEnumerable FindProductionAssetPaths() => + AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" }) + .Select(AssetDatabase.GUIDToAssetPath) + .Where(IsFirstPartyAsset); + + private static bool IsFirstPartyAsset(string path) => + path.StartsWith("Assets/", StringComparison.Ordinal) && + !path.StartsWith("Assets/ThirdParty/", StringComparison.Ordinal) && + !path.Contains("/Samples~/") && + !path.Contains("/Tests/"); + + private static string GetHierarchyPath(Transform target) + { + var names = new Stack(); + for (Transform current = target; current != null; current = current.parent) + { + names.Push(current.name); + } + + return string.Join("/", names); + } + } + + public static class RuntimeTypeResolver + { + private static readonly Dictionary Cache = + new Dictionary(StringComparer.Ordinal); + + public static Type Resolve(string typeName) + { + if (string.IsNullOrWhiteSpace(typeName)) return null; + if (Cache.TryGetValue(typeName, out Type cached)) return cached; + + Type resolved = Type.GetType(typeName, false); + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (resolved != null) break; + resolved = assembly.GetType(typeName, false); + if (resolved != null) break; + + try + { + resolved = assembly.GetTypes().FirstOrDefault(type => type.Name == typeName); + } + catch (ReflectionTypeLoadException exception) + { + resolved = exception.Types.FirstOrDefault(type => type != null && type.Name == typeName); + } + } + + Cache[typeName] = resolved; + return resolved; + } + } +} diff --git a/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs.meta b/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs.meta new file mode 100644 index 0000000..5ce2346 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAProductionMigrator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a657376a5eb4499ca885fc333235b873 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs b/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs new file mode 100644 index 0000000..2d56855 --- /dev/null +++ b/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs @@ -0,0 +1,31 @@ +using NUnit.Framework; +using ZoneUA.EditorValidation; + +namespace ZoneUA.EditorValidation.Tests +{ + public sealed class ProductionCompositionTests + { + [Test] + public void Catalog_contains_core_production_rules() + { + Assert.That(ProductionCompositionCatalog.Rules.Count, Is.GreaterThanOrEqualTo(6)); + } + + [Test] + public void Report_is_clean_only_without_missing_or_errors() + { + var report = new CompositionMigrationReport(); + Assert.That(report.IsClean, Is.True); + report.Add(CompositionMigrationStatus.Added, "a", "b", "c"); + Assert.That(report.IsClean, Is.True); + report.Add(CompositionMigrationStatus.Missing, "a", "b", "c"); + Assert.That(report.IsClean, Is.False); + } + + [Test] + public void Runtime_type_resolver_finds_unity_component() + { + Assert.That(RuntimeTypeResolver.Resolve("UnityEngine.Transform"), Is.Not.Null); + } + } +} diff --git a/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs.meta b/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs.meta new file mode 100644 index 0000000..92e2da8 --- /dev/null +++ b/Assets/_ZoneUA/Tests/Editor/ProductionCompositionTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b3d99662e58448ab34b96e3a6508c34 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Docs/PRODUCTION_COMPOSITION_MIGRATION.md b/Docs/PRODUCTION_COMPOSITION_MIGRATION.md new file mode 100644 index 0000000..bacf029 --- /dev/null +++ b/Docs/PRODUCTION_COMPOSITION_MIGRATION.md @@ -0,0 +1,121 @@ +# Production prefab and scene composition migration + +This module applies the architecture refactors to real Unity prefabs and loaded scenes through Unity Editor APIs. It intentionally does not edit prefab or scene YAML outside Unity. + +## Why the migration runs inside Unity + +Prefab assets may contain nested prefab links, overrides, managed references and GUID-backed object references. `PrefabUtility.LoadPrefabContents` and `PrefabUtility.SaveAsPrefabAsset` preserve those relationships, whereas direct text replacement can corrupt them. + +## Menu commands + +Open Unity and use: + +- `Zone UA/Migration/Audit Production Composition` +- `Zone UA/Migration/Migrate Selected Prefabs` +- `Zone UA/Migration/Migrate All Production Prefabs` +- `Zone UA/Migration/Audit Open Scenes` +- `Zone UA/Migration/Migrate Open Scenes` + +Always run the audit first and commit the repository before running a bulk migration. + +## Composition rules + +### Player root + +An object containing `CharacterCustomController` must also contain: + +- `Health` +- `Death` +- `PlayerInputRouter` +- `WeaponSwitcher` + +These components are safe to add automatically, but their serialized references still need Inspector review. + +### NPC actor + +An object containing `NPCController` must also contain: + +- `Health` +- `Death` +- `FactionMember` + +### Weapon + +An object containing `WeaponController` must also contain: + +- `Weapon` +- `ProjectileSpawner` +- `ShellEjector` +- `WeaponAudio` +- `WeaponRecoil` + +The migrator adds missing components but does not guess muzzle transforms, shell points, audio clips, definitions or prefab references. + +### Damage presentation + +Objects containing `Health` are audited for `DamageEffectsPresenter`. This is report-only because destructibles and actors may need different effect policies and references. + +### World root + +An object containing `MapGenerator` must also contain `ChunkManager`. + +### Ammo HUD + +Objects containing `UIAmmoSystem` are audited for `WeaponAmmoPresenter`. This is report-only because the presenter requires explicit references to the active `WeaponSwitcher` and ammo view. + +## Safe workflow + +1. Open the project in Unity 6000.5.5f1. +2. Allow package import and script compilation to finish. +3. Run `Zone UA/Validation/Validate Project`. +4. Run `Audit Production Composition`. +5. Migrate a small representative prefab set first. +6. Review every added component and assign definitions, transforms, prefabs, masks and views. +7. Run EditMode tests. +8. Open production scenes and run `Audit Open Scenes`. +9. Run `Migrate Open Scenes`, review the diff and save scenes manually. +10. Perform player, NPC, weapon, HUD and world-generation smoke tests. + +## Required Inspector review after automatic migration + +### Player + +- assign `ZoneUAInput.inputactions` to `PlayerInputRouter` +- assign `CharacterCustomController` +- assign `WeaponSwitcher` +- verify `Health`, `Death` and damage presentation + +### NPC + +- assign `NpcDefinition` +- assign `FactionDefinition` +- verify detection and line-of-sight masks +- verify weapon prefab and patrol points + +### Weapon + +- assign `WeaponDefinition` +- configure projectile muzzle +- configure shell ejection point +- configure audio source and clips +- configure recoil values or definition values +- verify runtime spawner adapter + +### HUD + +- assign `WeaponSwitcher` +- assign `UIAmmoSystem` +- verify unarmed visibility behaviour + +### World + +- assign `WorldGenerationSettings` +- assign generation root +- point `ChunkManager` to the same generated root +- validate biome assets + +## Limitations + +The tool only adds components that are unambiguously safe. It never guesses scene object references or content assets. Report-only rules remain unresolved until a designer wires them in the Inspector. + +The tool has not been executed in this environment. Unity compilation, prefab saving and scene migration must be run locally in Unity 6000.5.5f1. diff --git a/Docs/PRODUCTION_COMPOSITION_MIGRATION.md.meta b/Docs/PRODUCTION_COMPOSITION_MIGRATION.md.meta new file mode 100644 index 0000000..c26a14b --- /dev/null +++ b/Docs/PRODUCTION_COMPOSITION_MIGRATION.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 40cf4e25da304937ab6ac85c467313f4 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: