diff --git a/com.unity.netcode.gameobjects/CHANGELOG.md b/com.unity.netcode.gameobjects/CHANGELOG.md index 0bccbd8f86..8f1e988020 100644 --- a/com.unity.netcode.gameobjects/CHANGELOG.md +++ b/com.unity.netcode.gameobjects/CHANGELOG.md @@ -10,6 +10,8 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Added +- `netcode.gameobjects get_object` returns each NetworkBehaviour's `NetworkVariable` and `NetworkList` values as the peer sees them, and the child path of nested behaviours. `--behaviour` limits the values to one behaviour type, and `--variables false` gives the previous short form. (#4258) +- `netcode.gameobjects audit` checks in-scene NetworkObjects for a missing network id (`GlobalObjectIdHash` 0, or a prefab instance still carrying its prefab's id), and takes `--scope scenes` to run only that check. (#4258) - ILPP diagnostic errors should now be clickable in the editor to go to the source of the issue. (#4250) ### Changed @@ -22,6 +24,7 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Fixed +- Issue where a `NetworkObject` added to a scene before the scene was first saved, for example by an editor script, was saved without an id of its own: a `GlobalObjectIdHash` of 0, so it never spawned, or for a prefab instance the prefab's id, shared by every instance. Saving the scene, or saving it as a copy, now assigns the missing ids and saves it again. (#4258) - Fixed issue where a `NetworkTransform` component placed on the child of the `NetworkObject` component failed to render the inspector. (#4261) - Issue where every `NetworkObject` that started before a session logged a "Did not register because there is no session in progress!" warning when `NetworkManager.LogLevel` was `Developer`. Only `GhostObject` instances log it now. (#4245) - Fixed a NullReferenceException that would be thrown if a MonoBehaviour derived from NetworkManager defines it's own Awake or OnEnable. (#4244) diff --git a/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md b/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md index 313a55b689..b19688b3b7 100644 --- a/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md +++ b/com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md @@ -27,7 +27,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c | `status` | Each NetworkManager: role (host, server, client), connection state, local client id, topology, session owner, client and object counts, ticks, transport address, and whether the session runs hybrid prefabs. | | `list_clients` | Connected clients with their player object, owned object count and round trip time. | | `list_objects` | Spawned NetworkObjects as this peer sees them, filtered by name or owner. | -| `get_object` | One NetworkObject: owner, authority, ownership flags and who can change them, observers and NetworkBehaviours. | +| `get_object` | One NetworkObject: owner, authority, ownership flags and who can change them, observers, NetworkBehaviours, and each behaviour's child path and `NetworkVariable` and `NetworkList` values as this peer sees them. `--behaviour` limits the values to one behaviour type; `--variables false` leaves out the paths and values. | | `spawn` | Instantiate and spawn a registered network prefab at a position, optionally for an owner or as a player object. | | `despawn` | Despawn a NetworkObject, optionally keeping the GameObject. | | `change_owner` | Give a NetworkObject to another client, following the topology's ownership rules. | @@ -35,7 +35,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c | `list_prefabs` | Network prefabs lists with their prefabs, and the lists and player prefab each NetworkManager uses. | | `register_prefab` | Add a network prefab to a network prefabs list and save the list. | | `make_prefab` | Add a NetworkObject to a prefab's root and report its prefab id hash. | -| `audit` | Find setup problems that otherwise show when a session starts: in NetworkManagers (transport, topology, prefab lists, player prefab, hybrid prefab requirements) and in network prefabs (NetworkBehaviours without a NetworkObject, nested NetworkObjects, duplicate prefab ids, unregistered prefabs). `--scope config` or `--scope prefabs` runs one half. | +| `audit` | Find setup problems that otherwise show when a session starts: in NetworkManagers (transport, topology, prefab lists, player prefab, hybrid prefab requirements), in in-scene NetworkObjects (no network id, so they never spawn), and in network prefabs (NetworkBehaviours without a NetworkObject, nested NetworkObjects, duplicate prefab ids, unregistered prefabs). `--scope config`, `--scope scenes` or `--scope prefabs` runs one part. | ### netcode.gameobjects.profiler diff --git a/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs b/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs index f1d21cc285..6b9139b891 100644 --- a/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs +++ b/com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs @@ -33,11 +33,13 @@ private static object ListObjects( [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null) => NgoCliOutput.ToWire(NgoCliQueries.ListObjects(manager, nameContains, owner, limit)); - [CliGroupCommand(k_Group, "One spawned NetworkObject: owner, authority, ownership flags and who may change them, observers, NetworkBehaviours, scene and position. Requires a running session.", Tags = new[] { Tag })] + [CliGroupCommand(k_Group, "One spawned NetworkObject: owner, authority, ownership flags and who may change them, observers, NetworkBehaviours, scene, position, and each behaviour's child path and NetworkVariable and NetworkList values as this peer sees them. Requires a running session.", Tags = new[] { Tag })] private static object GetObject( [CliArg("id", "NetworkObjectId, from netcode.gameobjects list_objects.", Required = true)] long id, - [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null) - => NgoCliOutput.ToWire(NgoCliQueries.GetObject(id, manager)); + [CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null, + [CliArg("behaviour", "Only this NetworkBehaviour's variables, by type name.")] string behaviour = null, + [CliArg("variables", "Include each behaviour's child path and NetworkVariable values. False gives the short form.")] bool variables = true) + => NgoCliOutput.ToWire(NgoCliQueries.GetObject(id, manager, behaviour, variables)); [CliGroupCommand(k_Group, "Instantiate and spawn a registered network prefab. Server or host in client-server; any client in distributed authority (which then owns it). Returns the spawned object.", Tags = new[] { Tag })] private static object Spawn( @@ -89,9 +91,9 @@ private static object MakePrefab( [CliArg("dry-run", "Validate and report without changing the prefab.")] bool dryRun = false) => NgoCliOutput.ToWire(NgoCliQueries.MakePrefab(prefab, dryRun)); - [CliGroupCommand(k_Group, "Check the project for problems that otherwise show when a session starts: NetworkManager setups in the open scenes (transport, topology, prefab lists, player prefab, hierarchy, hybrid prefab requirements) and network prefabs (NetworkBehaviours without a NetworkObject, nested or misplaced NetworkObjects, NetworkManagers in network prefabs, missing or duplicate prefab ids, unregistered prefabs, broken list entries).", Tags = new[] { Tag })] + [CliGroupCommand(k_Group, "Check the project for problems that otherwise show when a session starts: NetworkManager setups in the open scenes (transport, topology, prefab lists, player prefab, hierarchy, hybrid prefab requirements), in-scene NetworkObjects without a network id, and network prefabs (NetworkBehaviours without a NetworkObject, nested or misplaced NetworkObjects, NetworkManagers in network prefabs, missing or duplicate prefab ids, unregistered prefabs, broken list entries).", Tags = new[] { Tag })] private static object Audit( - [CliArg("scope", "all, config (NetworkManagers) or prefabs.")] string scope = "all", + [CliArg("scope", "all, config (NetworkManagers), scenes (in-scene NetworkObjects) or prefabs.")] string scope = "all", [CliArg("folder", "Prefabs only: prefabs under this folder, e.g. Assets/Prefabs.")] string folder = null, [CliArg("limit", "Maximum issues returned (counts include all).")] int limit = 200, [CliArg("manager", "Config only: this NetworkManager (name or hierarchy path). Omit for all.")] string manager = null) diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs index f20910dda2..74e12fde1b 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs @@ -109,6 +109,30 @@ internal class ObjectDetail : ObjectSummary public OwnershipInfo Ownership; public List Observers; public List Behaviours = new List(); + /// Each behaviour's NetworkVariable values as this peer sees them; null when variables weren't asked for. + public List State; + } + + internal class BehaviourState + { + public string Behaviour; + /// The behaviour's GameObject below the NetworkObject; null on the NetworkObject's own GameObject. + public string Path; + public List Variables = new List(); + } + + internal class VariableState + { + public string Name; + public string Type; + public object Value; + /// For a list or other collection: the full element count, though at most MaxElementsShown are shown. + public int? Count; + public bool Truncated; + public NetworkVariableReadPermission ReadPerm; + public NetworkVariableWritePermission WritePerm; + /// Why there's no value: not sent to this client, or the read failed. + public string Note; } internal class OwnershipInfo @@ -246,6 +270,8 @@ internal class ProjectAuditResult public int? ManagersChecked; /// Set when network prefabs were checked. public int? PrefabsScanned; + /// Set when the NetworkObjects in the open scenes were checked. + public int? SceneObjectsChecked; public int Errors; public int Warnings; public bool Truncated; @@ -257,7 +283,7 @@ internal class AuditIssue /// error or warning. public string Severity; public string Code; - /// config (NetworkManagers) or prefabs. + /// config (NetworkManagers), scenes (in-scene NetworkObjects) or prefabs. public string Area; public string Asset; public string Message; diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs index 6d762de990..f7db6a2fb5 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs @@ -402,15 +402,16 @@ internal static MakePrefabResult MakePrefab(string prefab, bool dryRun) // --- Audit --- /// - /// Runs the NetworkManager checks (), the network prefab checks - /// (), or both, and returns their issues as one list, NetworkManagers first. + /// Runs the NetworkManager checks (), the in-scene NetworkObject checks + /// (), the network prefab checks (), or all three, and + /// returns their issues as one list in that order: NetworkManagers, then scenes, then prefabs. /// internal static ProjectAuditResult Audit(string scope, string folder, int limit, string managerFilter) { var normalized = string.IsNullOrWhiteSpace(scope) ? "all" : scope.Trim().ToLowerInvariant(); - if (normalized is not ("all" or "config" or "prefabs")) + if (normalized is not ("all" or "config" or "scenes" or "prefabs")) { - throw new ArgumentException("scope must be all, config or prefabs."); + throw new ArgumentException("scope must be all, config, scenes or prefabs."); } if (limit < 1) { @@ -419,7 +420,7 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, var result = new ProjectAuditResult(); var issues = new List(); - if (normalized != "prefabs") + if (normalized is "all" or "config") { // A project check shouldn't fail because the scene with the NetworkManager isn't open. if (normalized == "all" && string.IsNullOrWhiteSpace(managerFilter) && FindManagers().Count == 0) @@ -441,7 +442,24 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, } } } - if (normalized != "config") + if (normalized is "all" or "scenes") + { + var scenes = AuditScenes(); + result.SceneObjectsChecked = scenes.ObjectsChecked; + foreach (var issue in scenes.Issues) + { + if (issue.Severity == "error") + { + result.Errors++; + } + else + { + result.Warnings++; + } + issues.Add(issue); + } + } + if (normalized is "all" or "prefabs") { var prefabs = AuditPrefabs(folder, limit); result.PrefabsScanned = prefabs.PrefabsScanned; @@ -462,6 +480,64 @@ internal static ProjectAuditResult Audit(string scope, string folder, int limit, return result; } + /// + /// Checks the NetworkObjects placed in the open scenes for a missing scene id: GlobalObjectIdHash 0, or a + /// prefab instance still carrying its prefab asset's id. NGO can't match such an object across peers (several + /// instances share the prefab's id), so it doesn't spawn and a session that waits for it never starts. It + /// happens when a NetworkObject is added to a scene before the scene is first saved. + /// + internal static (int ObjectsChecked, List Issues) AuditScenes() + { + var issues = new List(); + var checkedCount = 0; + for (var i = 0; i < SceneManager.sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + if (!scene.isLoaded) + { + continue; + } + var unsaved = string.IsNullOrEmpty(scene.path); + var missing = new List(); + foreach (var networkObject in FindObjects.FromSceneByType(scene, true)) + { + // Objects spawned at runtime aren't in-scene objects; one built at runtime always has id 0. + if (networkObject.IsSpawned && !networkObject.InScenePlaced) + { + continue; + } + checkedCount++; + if (InSceneNetworkObjectIdRepair.NeedsSceneId(networkObject)) + { + missing.Add(GetHierarchyPath(networkObject.transform)); + } + } + if (missing.Count == 0) + { + continue; + } + var names = string.Join(", ", missing.Count > 10 ? missing.GetRange(0, 10) : missing) + (missing.Count > 10 ? $" and {missing.Count - 10} more" : ""); + issues.Add(unsaved + ? new AuditIssue + { + Severity = "warning", + Code = "SCENE_NOT_SAVED", + Area = "scenes", + Asset = SceneLabel(scene), + Message = $"{missing.Count} NetworkObject(s) in a scene that has never been saved have no network id of their own yet: {names}. Save the scene; NGO assigns the ids when it has a path.", + } + : new AuditIssue + { + Severity = "error", + Code = "IN_SCENE_ID_MISSING", + Area = "scenes", + Asset = scene.path, + Message = $"{missing.Count} in-scene NetworkObject(s) have no network id of their own (GlobalObjectIdHash 0, or a prefab instance still carrying its prefab's id), so they don't spawn: {names}. Save the scene to assign them (a scene saved by this NGO version gets them on save), or reopen it, mark it dirty and save.", + }); + } + return (checkedCount, issues); + } + /// /// Checks network prefabs for setup problems the editor otherwise reports one at a time, in the inspector or /// when a session starts: behaviours without a NetworkObject, nested or misplaced NetworkObjects, diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs new file mode 100644 index 0000000000..d1e39f9795 --- /dev/null +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using UnityEngine; + +namespace Unity.Netcode.GameObjects.Editor.Cli +{ + internal static partial class NgoCliQueries + { + /// Most elements shown for a list or other collection value; the count is always the full one. + internal const int MaxElementsShown = 32; + + /// How deep struct and class values are expanded into their fields before falling back to ToString. + private const int k_MaxValueDepth = 2; + + private static readonly Dictionary s_ValueProperties = new Dictionary(); + + /// + /// The NetworkVariable values of each NetworkBehaviour a NetworkObject owns, as this peer sees them. Nested + /// behaviours carry the path of their GameObject below the NetworkObject. A variable that can't be read + /// reports why instead of failing the whole object. + /// + internal static List DescribeBehaviourState(NetworkManager manager, NetworkObject networkObject, string behaviourFilter) + { + var states = new List(); + foreach (var behaviour in OwnedBehaviours(networkObject)) + { + if (!MatchesBehaviour(behaviour, behaviourFilter)) + { + continue; + } + var state = new BehaviourState + { + Behaviour = behaviour.GetType().Name, + Path = RelativePath(networkObject.transform, behaviour.transform), + }; + foreach (var variable in behaviour.NetworkVariableFields) + { + state.Variables.Add(DescribeVariable(manager, variable)); + } + states.Add(state); + } + if (states.Count == 0) + { + RequireBehaviour(networkObject, behaviourFilter); + } + return states; + } + + /// True when there's no filter, or the behaviour's type name or full name matches it. + private static bool MatchesBehaviour(NetworkBehaviour behaviour, string behaviourFilter) + { + if (string.IsNullOrEmpty(behaviourFilter)) + { + return true; + } + var type = behaviour.GetType(); + return string.Equals(type.Name, behaviourFilter, StringComparison.OrdinalIgnoreCase) + || string.Equals(type.FullName, behaviourFilter, StringComparison.OrdinalIgnoreCase); + } + + /// Throws when a behaviour filter matches none of the NetworkObject's behaviours, so a typo isn't silently ignored. + internal static void RequireBehaviour(NetworkObject networkObject, string behaviourFilter) + { + if (string.IsNullOrEmpty(behaviourFilter)) + { + return; + } + foreach (var behaviour in OwnedBehaviours(networkObject)) + { + if (MatchesBehaviour(behaviour, behaviourFilter)) + { + return; + } + } + throw new ArgumentException($"{networkObject.name} has no NetworkBehaviour named '{behaviourFilter}'. Its behaviours are listed under behaviours in netcode.gameobjects get_object."); + } + + /// The NetworkBehaviours NGO assigns to this NetworkObject: a nested NetworkObject owns the ones below it. + internal static IEnumerable OwnedBehaviours(NetworkObject networkObject) + { + foreach (var behaviour in networkObject.GetComponentsInChildren(true)) + { + if (behaviour.GetComponentInParent(true) == networkObject) + { + yield return behaviour; + } + } + } + + private static VariableState DescribeVariable(NetworkManager manager, NetworkVariableBase variable) + { + var state = new VariableState + { + Name = variable.Name, + Type = FriendlyTypeName(variable.GetType()), + ReadPerm = variable.ReadPerm, + WritePerm = variable.WritePerm, + }; + try + { + if (!manager.IsServer && !variable.CanClientRead(manager.LocalClientId)) + { + state.Note = $"Not sent to this client: read permission is {variable.ReadPerm}. Read it on the server or the owner."; + return state; + } + var valueProperty = GetValueProperty(variable.GetType()); + if (valueProperty != null) + { + state.Value = FormatTopLevel(valueProperty.GetValue(variable), state, manager); + } + else if (variable is IEnumerable collection) + { + state.Value = FormatTopLevel(collection, state, manager); + } + else if (GetEnumeratorMethod(variable.GetType()) is { } getEnumerator) + { + // NetworkList has a public GetEnumerator but doesn't implement IEnumerable. + state.Value = FormatTopLevel(new EnumeratorSource((IEnumerator)getEnumerator.Invoke(variable, null)), state, manager); + } + else + { + state.Value = variable.ToString(); + } + } + catch (Exception exception) + { + var inner = exception is TargetInvocationException { InnerException: not null } ? exception.InnerException : exception; + state.Note = $"Couldn't read the value: {inner.GetType().Name}: {inner.Message}"; + } + return state; + } + + /// The public instance Value property of NetworkVariable<T>, AnticipatedNetworkVariable<T> and similar, cached per type. + private static PropertyInfo GetValueProperty(Type variableType) + { + if (!s_ValueProperties.TryGetValue(variableType, out var property)) + { + property = variableType.GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); + if (property != null && (!property.CanRead || property.GetIndexParameters().Length > 0)) + { + property = null; + } + s_ValueProperties[variableType] = property; + } + return property; + } + + private static MethodInfo GetEnumeratorMethod(Type variableType) + { + var method = variableType.GetMethod("GetEnumerator", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); + return method != null && typeof(IEnumerator).IsAssignableFrom(method.ReturnType) ? method : null; + } + + /// Lets an enumerator from a duck-typed GetEnumerator be read as a collection. + private sealed class EnumeratorSource : IEnumerable + { + private readonly IEnumerator m_Enumerator; + + internal EnumeratorSource(IEnumerator enumerator) + { + m_Enumerator = enumerator; + } + + public IEnumerator GetEnumerator() => m_Enumerator; + } + + /// A variable's own collection reports its full size in Count and Truncated instead of a marker entry. + internal static object FormatTopLevel(object value, VariableState state, NetworkManager manager) + { + if (value is IDictionary dictionary) + { + var map = FormatDictionary(dictionary, 1, manager, out var total); + state.Count = total; + state.Truncated = total > MaxElementsShown; + return map; + } + if (value is IEnumerable collection && !IsScalar(value)) + { + var items = FormatList(collection, 1, manager, out var total); + state.Count = total; + state.Truncated = total > MaxElementsShown; + return items; + } + return FormatValue(value, 0, manager); + } + + /// The marker that ends a nested collection cut at . + internal static string MoreMarker(int hidden) => $"(+{hidden} more)"; + + /// + /// A dictionary whose keys are simple values (numbers, strings, enums) becomes a map keyed by their text. + /// Other keys, such as references or structs, can share the same text, so that dictionary becomes a list of + /// {key, value} pairs instead, with each key formatted like a value. + /// + private static object FormatDictionary(IDictionary dictionary, int depth, NetworkManager manager, out int total) + { + var shown = new List(); + var map = new Dictionary(); + var keysAreText = true; + total = 0; + foreach (DictionaryEntry entry in dictionary) + { + if (total < MaxElementsShown) + { + var value = FormatEntryPart(entry.Value, depth, manager); + shown.Add(new DictionaryEntry(entry.Key, value)); + keysAreText = keysAreText && IsTextKey(entry.Key) && map.TryAdd(Convert.ToString(entry.Key, CultureInfo.InvariantCulture), value); + } + total++; + } + if (keysAreText) + { + return map; + } + var pairs = new List(shown.Count); + foreach (var entry in shown) + { + pairs.Add(new Dictionary { ["key"] = FormatEntryPart(entry.Key, depth, manager), ["value"] = entry.Value }); + } + return pairs; + } + + private static object FormatEntryPart(object value, int depth, NetworkManager manager) + { + return depth <= k_MaxValueDepth ? FormatValue(value, depth, manager) : value?.ToString(); + } + + private static bool IsTextKey(object key) + { + return key is Enum || key is decimal || key.GetType().IsPrimitive || IsScalar(key); + } + + private static List FormatList(IEnumerable collection, int depth, NetworkManager manager, out int total) + { + var result = new List(); + total = 0; + foreach (var item in collection) + { + if (total < MaxElementsShown) + { + result.Add(depth <= k_MaxValueDepth ? FormatValue(item, depth, manager) : item?.ToString()); + } + total++; + } + return result; + } + + /// + /// Turns a NetworkVariable value into plain data the CLI can return: numbers, strings and enum names as they + /// are, Unity vectors, quaternions and colours as arrays, references as their ids and names, collections as + /// capped lists and maps, and other structs and classes as their public and serialized fields, a couple of + /// levels deep. References resolve on , the peer being read; null means + /// NetworkManager.Singleton. + /// + internal static object FormatValue(object value, int depth, NetworkManager manager = null) + { + switch (value) + { + case null: + return null; + case string or bool or char: + return value; + case Enum e: + return e.ToString(); + case float f: + return f; + case double d: + return d; + case Vector2 v: + return new[] { v.x, v.y }; + case Vector3 v: + return new[] { v.x, v.y, v.z }; + case Vector4 v: + return new[] { v.x, v.y, v.z, v.w }; + case Vector2Int v: + return new[] { v.x, v.y }; + case Vector3Int v: + return new[] { v.x, v.y, v.z }; + case Quaternion q: + return new[] { q.x, q.y, q.z, q.w }; + case Color c: + return new[] { c.r, c.g, c.b, c.a }; + case Color32 c: + return new[] { (int)c.r, c.g, c.b, c.a }; + case NetworkObjectReference reference: + return DescribeReference(reference, manager); + case NetworkBehaviourReference reference: + return DescribeReference(reference, manager); + case UnityEngine.Object unityObject: + // A destroyed object compares equal to null. + return unityObject ? unityObject.name : null; + } + + var type = value.GetType(); + if (type.IsPrimitive || value is decimal) + { + return value; + } + if (IsScalar(value)) + { + return value.ToString(); + } + // Nested collections have no Count of their own, so a cut one ends with a marker saying how much is hidden. + if (value is IDictionary dictionary) + { + var formatted = FormatDictionary(dictionary, depth + 1, manager, out var total); + if (total > MaxElementsShown) + { + if (formatted is Dictionary map) + { + map[MoreMarker(total - MaxElementsShown)] = null; + } + else + { + ((List)formatted).Add(MoreMarker(total - MaxElementsShown)); + } + } + return formatted; + } + if (value is IEnumerable enumerable) + { + var items = FormatList(enumerable, depth + 1, manager, out var total); + if (total > MaxElementsShown) + { + items.Add(MoreMarker(total - MaxElementsShown)); + } + return items; + } + if (depth >= k_MaxValueDepth) + { + return value.ToString(); + } + var fields = GetDataFields(type); + if (fields.Count == 0) + { + return value.ToString(); + } + var members = new Dictionary(); + foreach (var (name, field) in fields) + { + members[name] = FormatValue(field.GetValue(value), depth + 1, manager); + } + return members; + } + + private static readonly Dictionary> s_DataFields = new Dictionary>(); + + /// + /// The fields that hold a struct or class's data, as Unity serializes it: public fields, and non-public ones + /// marked [SerializeField] (an auto-property's [field: SerializeField] backing field goes by the property name). + /// + private static List<(string Name, FieldInfo Field)> GetDataFields(Type type) + { + if (!s_DataFields.TryGetValue(type, out var fields)) + { + fields = new List<(string, FieldInfo)>(); + foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (field.IsPublic || field.IsDefined(typeof(SerializeField), false)) + { + var name = field.Name; + if (name.StartsWith("<", StringComparison.Ordinal) && name.EndsWith(">k__BackingField", StringComparison.Ordinal)) + { + name = name.Substring(1, name.Length - "<>k__BackingField".Length); + } + fields.Add((name, field)); + } + } + s_DataFields[type] = fields; + } + return fields; + } + + /// + /// A default reference (id 0, never assigned to a spawned object) or one made from null (id ulong.MaxValue) + /// points at nothing. + /// + private static bool IsEmpty(NetworkObjectReference reference) => reference.NetworkObjectId is 0 or ulong.MaxValue; + + /// An empty reference is null; one this peer can't resolve keeps its ids and has no name. + private static Dictionary DescribeReference(NetworkObjectReference reference, NetworkManager manager) + { + if (IsEmpty(reference)) + { + return null; + } + var result = new Dictionary { ["networkObjectId"] = (long)reference.NetworkObjectId }; + if (reference.TryGet(out var referenced, manager)) + { + result["name"] = referenced.name; + } + return result; + } + + private static Dictionary DescribeReference(NetworkBehaviourReference reference, NetworkManager manager) + { + if (IsEmpty(reference.ObjectReference)) + { + return null; + } + var result = new Dictionary + { + ["networkObjectId"] = (long)reference.ObjectReference.NetworkObjectId, + ["behaviourId"] = (int)reference.NetworkBehaviourId, + }; + if (reference.TryGet(out NetworkBehaviour referenced, manager)) + { + result["behaviour"] = referenced.GetType().Name; + result["name"] = referenced.name; + } + return result; + } + + /// Values best shown as their text: Unity.Collections fixed strings, and Guid-like types with no fields. + private static bool IsScalar(object value) + { + if (value is string) + { + return true; + } + var type = value.GetType(); + return (type.Namespace == "Unity.Collections" && type.Name.StartsWith("FixedString", StringComparison.Ordinal)) + || value is Guid || value is DateTime || value is TimeSpan; + } + + /// NetworkVariable<Int32> rather than NetworkVariable`1. + private static string FriendlyTypeName(Type type) + { + if (!type.IsGenericType) + { + return type.Name; + } + var name = type.Name; + var tick = name.IndexOf('`'); + if (tick >= 0) + { + name = name.Substring(0, tick); + } + var arguments = type.GetGenericArguments(); + var names = new string[arguments.Length]; + for (var i = 0; i < arguments.Length; i++) + { + names[i] = FriendlyTypeName(arguments[i]); + } + return $"{name}<{string.Join(", ", names)}>"; + } + + /// The path of below , or null when they're the same. + private static string RelativePath(Transform root, Transform child) + { + if (child == root) + { + return null; + } + var parts = new List(); + for (var current = child; current != null && current != root; current = current.parent) + { + parts.Add(current.name); + } + parts.Reverse(); + return string.Join("/", parts); + } + } +} diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta new file mode 100644 index 0000000000..91677bb3b0 --- /dev/null +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Variables.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 942305f4d28e412fadfb22044513d65d \ No newline at end of file diff --git a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs index 39f85b656c..113781feea 100644 --- a/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs +++ b/com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs @@ -293,11 +293,20 @@ internal static ObjectListResult ListObjects(string managerFilter, string nameCo return result; } - internal static ObjectDetail GetObject(long networkObjectId, string managerFilter) + internal static ObjectDetail GetObject(long networkObjectId, string managerFilter, string behaviourFilter = null, bool variables = true) { var manager = ResolveRunningManager(managerFilter); var networkObject = FindSpawnedObject(manager, networkObjectId); - return Describe(manager, networkObject); + var detail = Describe(manager, networkObject); + if (variables) + { + detail.State = DescribeBehaviourState(manager, networkObject, behaviourFilter); + } + else + { + RequireBehaviour(networkObject, behaviourFilter); + } + return detail; } internal static ObjectDetail Describe(NetworkManager manager, NetworkObject networkObject) @@ -309,13 +318,9 @@ internal static ObjectDetail Describe(NetworkManager manager, NetworkObject netw detail.DestroyWithScene = networkObject.DestroyWithScene; detail.DontDestroyWithOwner = networkObject.DontDestroyWithOwner; detail.Ownership = DescribeOwnership(manager, networkObject); - foreach (var behaviour in networkObject.GetComponentsInChildren(true)) + foreach (var behaviour in OwnedBehaviours(networkObject)) { - // As NGO assigns them: a nested NetworkObject owns the behaviours below it. - if (behaviour.GetComponentInParent(true) == networkObject) - { - detail.Behaviours.Add(behaviour.GetType().Name); - } + detail.Behaviours.Add(behaviour.GetType().Name); } // Observers are only tracked by the authority that decides visibility. diff --git a/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs b/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs index 8c326e5107..9d06f7a852 100644 --- a/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs +++ b/com.unity.netcode.gameobjects/Editor/InScenePlacedProcessor.cs @@ -82,6 +82,196 @@ public static void ReportSceneIssues(Scene scene, bool hasAwakeRun) } } + /// + /// Gives in-scene placed s the scene id they missed, when their scene is saved. + /// + /// + /// NetworkObject.OnValidate can only generate the GlobalObjectIdHash once the scene has an asset path, and a + /// later revalidation of a scene object doesn't mark the scene dirty. So a NetworkObject added to a new scene (by + /// an editor script, for instance) and saved with it keeps the id it had before: 0 for a plain NetworkObject, + /// the prefab asset's id for a prefab instance. The saved file then holds an object that never spawns, or + /// several instances that share one id. After each save, this regenerates those ids and saves the scene again; + /// for a save as copy, it repairs the copy, since the scene in memory isn't the one that was written. + /// + [InitializeOnLoad] + internal static class InSceneNetworkObjectIdRepair + { + private static bool s_Saving; + + /// The path each scene is being saved to, when it has objects that need an id. + private static readonly System.Collections.Generic.Dictionary s_PendingSaves = new System.Collections.Generic.Dictionary(); + + static InSceneNetworkObjectIdRepair() + { + UnityEditor.SceneManagement.EditorSceneManager.sceneSaving += OnSceneSaving; + UnityEditor.SceneManagement.EditorSceneManager.sceneSaved += OnSceneSaved; + } + + /// + /// True when an in-scene NetworkObject has no scene id of its own: 0, or for a prefab instance the id of the + /// prefab asset it was instantiated from. + /// + internal static bool NeedsSceneId(NetworkObject networkObject) + { + return networkObject.GlobalObjectIdHash == 0 + || (networkObject.GlobalObjectIdHash == SourcePrefabId(networkObject) && !IsEditedPrefab(networkObject)); + } + + /// The GlobalObjectIdHash of the prefab asset a prefab instance comes from; 0 for other objects. + internal static uint SourcePrefabId(NetworkObject networkObject) + { + if (!PrefabUtility.IsPartOfPrefabInstance(networkObject)) + { + return 0; + } + var source = PrefabUtility.GetCorrespondingObjectFromSource(networkObject); + return source != null ? source.GlobalObjectIdHash : 0; + } + + /// A prefab open in prefab mode deliberately carries its asset's id. + private static bool IsEditedPrefab(NetworkObject networkObject) + { + return UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(networkObject.gameObject) != null; + } + + /// Regenerates the id of each NetworkObject in the scene that has none of its own; returns how many now have one. + internal static int Repair(Scene scene) + { + var repaired = 0; + if (!scene.IsValid() || !scene.isLoaded || string.IsNullOrEmpty(scene.path)) + { + return repaired; + } + foreach (var networkObject in FindObjects.FromSceneByType(scene, true)) + { + if (!NeedsSceneId(networkObject)) + { + continue; + } + networkObject.OnValidate(); + RecordInstanceId(networkObject); + if (!NeedsSceneId(networkObject)) + { + repaired++; + } + } + return repaired; + } + + /// + /// OnValidate records the id as a prefab override, and the source prefab's id, only for objects it marks + /// in-scene placed, which needs the scene in the build list. Without the override, the saved instance would + /// still read the prefab's id. Without the source id, a session with scene management off would send the new + /// scene id, which clients can't find among the registered prefabs. + /// + private static void RecordInstanceId(NetworkObject networkObject) + { + if (!PrefabUtility.IsPartOfPrefabInstance(networkObject)) + { + return; + } + if (networkObject.InScenePlacedSourceGlobalObjectIdHash == 0) + { + networkObject.InScenePlacedSourceGlobalObjectIdHash = SourcePrefabId(networkObject); + } + PrefabUtility.RecordPrefabInstancePropertyModifications(networkObject); + } + + private static bool HasObjectsNeedingIds(Scene scene) + { + foreach (var networkObject in FindObjects.FromSceneByType(scene, true)) + { + if (NeedsSceneId(networkObject)) + { + return true; + } + } + return false; + } + + private static void OnSceneSaving(Scene scene, string path) + { + if (s_Saving || EditorApplication.isPlayingOrWillChangePlaymode) + { + return; + } + if (HasObjectsNeedingIds(scene)) + { + s_PendingSaves[scene] = path; + } + else + { + s_PendingSaves.Remove(scene); + } + } + + private static void OnSceneSaved(Scene scene) + { + if (s_Saving || EditorApplication.isPlayingOrWillChangePlaymode) + { + return; + } + if (!s_PendingSaves.TryGetValue(scene, out var savedTo)) + { + return; + } + s_PendingSaves.Remove(scene); + s_Saving = true; + try + { + if (!string.IsNullOrEmpty(savedTo) && !PathsMatch(savedTo, scene.path)) + { + RepairCopy(savedTo); + } + else if (Repair(scene) > 0) + { + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene(scene); + } + } + finally + { + s_Saving = false; + } + } + + private static bool PathsMatch(string a, string b) + { + return string.Equals(a?.Replace('\\', '/'), b?.Replace('\\', '/'), System.StringComparison.OrdinalIgnoreCase); + } + + /// + /// A save as copy wrote the scene to while the scene in memory kept its own path (or + /// none). Loading the copy gives its objects their ids in memory only, so open it, record the ids, and save it. + /// If a scene at that path is already open, its contents in memory are not what was just written, and saving + /// it would overwrite the copy; leave the file alone and say how to fix it. + /// + private static void RepairCopy(string path) + { + var loaded = SceneManager.GetSceneByPath(path); + if (loaded.IsValid() && loaded.isLoaded) + { + Debug.LogWarning($"[Netcode] Didn't give the {nameof(NetworkObject)}s in the copy at {path} their network ids, because a scene at that path is open. Close it, reopen {path}, mark it dirty and save it."); + return; + } + var copy = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(path, UnityEditor.SceneManagement.OpenSceneMode.Additive); + try + { + foreach (var networkObject in FindObjects.FromSceneByType(copy, true)) + { + networkObject.OnValidate(); + RecordInstanceId(networkObject); + } + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(copy); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene(copy); + } + finally + { + UnityEditor.SceneManagement.EditorSceneManager.CloseScene(copy, true); + } + } + } + /// /// An that sets the property to false for all s in prefabs. /// Ensures that InScenePlaced is always false for all prefab objects. diff --git a/com.unity.netcode.gameobjects/Runtime/Serialization/NetworkBehaviourReference.cs b/com.unity.netcode.gameobjects/Runtime/Serialization/NetworkBehaviourReference.cs index 0b2e406e4f..2e7543fdae 100644 --- a/com.unity.netcode.gameobjects/Runtime/Serialization/NetworkBehaviourReference.cs +++ b/com.unity.netcode.gameobjects/Runtime/Serialization/NetworkBehaviourReference.cs @@ -13,6 +13,12 @@ public struct NetworkBehaviourReference : INetworkSerializable, IEquatableThe referenced behaviour's NetworkObject, for tools that report an unresolved reference. + internal NetworkObjectReference ObjectReference => m_NetworkObjectReference; + + /// The referenced behaviour's id on its NetworkObject, for tools that report an unresolved reference. + internal ushort NetworkBehaviourId => m_NetworkBehaviourId; + /// /// Creates a new instance of the struct. /// diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs index 488095d78d..bf5b31f006 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Cli/Commands/NetcodeGameObjectsCliCommandsTests.cs @@ -27,7 +27,7 @@ internal class NetcodeGameObjectsCliCommandsTests ["netcode.gameobjects status"] = new string[0], ["netcode.gameobjects list_clients"] = new[] { "manager" }, ["netcode.gameobjects list_objects"] = new[] { "name-contains", "owner", "limit", "manager" }, - ["netcode.gameobjects get_object"] = new[] { "id*", "manager" }, + ["netcode.gameobjects get_object"] = new[] { "id*", "manager", "behaviour", "variables" }, ["netcode.gameobjects spawn"] = new[] { "prefab*", "position", "owner", "player-object", "manager" }, ["netcode.gameobjects despawn"] = new[] { "id*", "destroy", "manager" }, ["netcode.gameobjects change_owner"] = new[] { "id*", "owner*", "manager" }, diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs index b25b7d1c1c..bf02643df5 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs @@ -7,6 +7,7 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using NUnit.Framework; +using Unity.Collections; using Unity.Netcode.GameObjects.Editor.Cli; using Unity.Netcode.GameObjects.Editor.Configuration; using Unity.Netcode.Transports.UTP; @@ -438,6 +439,109 @@ public void AuditPrefabs_FindsSetupProblems() Assert.Throws(() => NgoCliQueries.Audit("config", null, 50, null), "Asking for the NetworkManager checks needs one."); } + /// + /// A NetworkObject added to a scene before its first save has no network id. Saving gives it one (the save + /// hook regenerates it and saves again), and audit reports any in-scene object still without one. + /// + [Test] + public void InSceneNetworkObject_GetsItsIdOnSave_AndAuditReportsMissingIds() + { + var gameManager = new GameObject("GameManager", typeof(NetworkObject)); + var networkObject = gameManager.GetComponent(); + Assert.AreEqual(0u, networkObject.GlobalObjectIdHash, "A scene with no path can't give it an id yet."); + + var unsaved = NgoCliQueries.Audit("scenes", null, 50, null); + Assert.AreEqual(1, unsaved.SceneObjectsChecked); + Assert.AreEqual("SCENE_NOT_SAVED", Only(unsaved.Issues).Code); + Assert.IsNull(unsaved.ManagersChecked, "scope scenes skips the NetworkManager checks."); + + var scenePath = $"{k_Folder}/CliIdScene.unity"; + Assert.IsTrue(EditorSceneManager.SaveScene(gameManager.scene, scenePath)); + Assert.AreNotEqual(0u, networkObject.GlobalObjectIdHash, "Saving assigns the id."); + var assigned = networkObject.GlobalObjectIdHash; + + // The id has to be in the saved file, which is what clones and builds load. Reopening alone doesn't prove + // it: OnValidate regenerates the id in memory when the scene loads. + StringAssert.Contains($"GlobalObjectIdHash: {assigned}", System.IO.File.ReadAllText(scenePath)); + EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single); + var reopened = Only(new List(FindObjects.FromSceneByType(UnityEngine.SceneManagement.SceneManager.GetActiveScene(), true))); + Assert.AreEqual(assigned, reopened.GlobalObjectIdHash); + Assert.IsEmpty(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + + // A scene saved before this fix can still hold an object with no id. + reopened.GlobalObjectIdHash = 0; + var missing = Only(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + Assert.AreEqual("IN_SCENE_ID_MISSING", missing.Code); + Assert.AreEqual("error", missing.Severity); + Assert.AreEqual(scenePath, missing.Asset); + StringAssert.Contains("GameManager", missing.Message); + + EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + Assert.Throws(() => NgoCliQueries.Audit("everything", null, 50, null)); + } + + /// + /// A prefab instance placed in a scene before its first save carries the prefab asset's id, so every instance + /// shares it. Saving gives each its own id, written to the file as an override, and audit reports an + /// instance still carrying the prefab's id. + /// + [Test] + public void InScenePrefabInstances_GetTheirOwnIdsOnSave() + { + var prefab = CreatePrefab("CliSpawnPoint", typeof(NetworkObject)); + var prefabId = prefab.GetComponent().GlobalObjectIdHash; + Assert.AreNotEqual(0u, prefabId); + var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene(); + var first = ((GameObject)PrefabUtility.InstantiatePrefab(prefab, scene)).GetComponent(); + var second = ((GameObject)PrefabUtility.InstantiatePrefab(prefab, scene)).GetComponent(); + Assert.AreEqual(prefabId, first.GlobalObjectIdHash, "Before the scene has a path, an instance carries its prefab's id."); + + var unsaved = Only(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + Assert.AreEqual("SCENE_NOT_SAVED", unsaved.Code); + StringAssert.Contains("2 NetworkObject(s)", unsaved.Message); + + var scenePath = $"{k_Folder}/CliPrefabIdScene.unity"; + Assert.IsTrue(EditorSceneManager.SaveScene(scene, scenePath)); + var ids = new[] { first.GlobalObjectIdHash, second.GlobalObjectIdHash }; + CollectionAssert.DoesNotContain(ids, prefabId, "Saving gives each instance its own id."); + Assert.AreNotEqual(ids[0], ids[1]); + var text = System.IO.File.ReadAllText(scenePath); + foreach (var id in ids) + { + Assert.IsTrue(Regex.IsMatch(text, $@"propertyPath: GlobalObjectIdHash\s+value: {id}\b"), $"The file overrides the id with {id}."); + } + // The scene isn't in the build list, so OnValidate doesn't record the source prefab; without it, a session + // with scene management off would send the scene id, which clients can't spawn. + Assert.AreEqual(prefabId, first.InScenePlacedSourceGlobalObjectIdHash); + Assert.AreEqual(prefabId, second.InScenePlacedSourceGlobalObjectIdHash); + Assert.IsTrue(Regex.IsMatch(text, $@"propertyPath: InScenePlacedSourceGlobalObjectIdHash\s+value: {prefabId}\b"), "The file records the source prefab's id."); + Assert.IsEmpty(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + + // A scene saved before this fix can still hold an instance with its prefab's id. + second.GlobalObjectIdHash = prefabId; + var missing = Only(NgoCliQueries.Audit("scenes", null, 50, null).Issues); + Assert.AreEqual("IN_SCENE_ID_MISSING", missing.Code); + StringAssert.Contains("prefab", missing.Message); + } + + /// + /// Saving an unsaved scene as a copy writes the copy while the scene in memory keeps no path, so the save hook + /// repairs the copy: it's written with an id, and isn't left open. + /// + [Test] + public void SaveAsCopy_WritesTheCopyWithIds() + { + var gameManager = new GameObject("GameManager", typeof(NetworkObject)); + var copyPath = $"{k_Folder}/CliCopyScene.unity"; + Assert.IsTrue(EditorSceneManager.SaveScene(gameManager.scene, copyPath, true)); + Assert.IsTrue(string.IsNullOrEmpty(gameManager.scene.path), "The scene in memory stays unsaved."); + Assert.AreEqual(1, UnityEngine.SceneManagement.SceneManager.sceneCount, "The copy isn't left open."); + + var saved = Regex.Match(System.IO.File.ReadAllText(copyPath), @"GlobalObjectIdHash: (\d+)"); + Assert.IsTrue(saved.Success); + Assert.AreNotEqual("0", saved.Groups[1].Value, "The copy is written with an id."); + } + // --- Config --- [Test] @@ -778,6 +882,238 @@ public IEnumerator RunningHost_SupportsTheRuntimeQueries() StringAssert.Contains("stopped as the server", stoppedServer.Message); } + internal enum CliTestPhase { Waiting, Playing } + + internal struct CliTestScore : INetworkSerializeByMemcpy + { + public int Points; + public FixedString32Bytes Label; + } + + internal struct CliTestKey + { + public int Id; + } + + internal class CliStateBehaviour : NetworkBehaviour + { + public NetworkVariable Counter = new NetworkVariable(); + public NetworkVariable Spot = new NetworkVariable(); + public NetworkVariable Phase = new NetworkVariable(); + public NetworkVariable Title = new NetworkVariable(); + public NetworkVariable Score = new NetworkVariable(); + public NetworkVariable Secret = new NetworkVariable(readPerm: NetworkVariableReadPermission.Owner); + public NetworkVariable> Scores = new NetworkVariable>(new Dictionary()); + public NetworkVariable Target = new NetworkVariable(); + public NetworkList Hits; + + private void Awake() + { + // NetworkList allocates native memory, so it's created here rather than in a field initializer. + Hits = new NetworkList(); + } + } + + internal class CliChildBehaviour : NetworkBehaviour + { + public NetworkVariable Lit = new NetworkVariable(); + } + + /// Data Unity serializes from non-public fields, which FormatValue shows like public ones. + internal struct CliTestStats + { + public int Visible; + [SerializeField] + private int m_Hp; + [field: SerializeField] + public int Level { get; set; } + private int m_Hidden; + + public CliTestStats(int visible, int hp, int level, int hidden) + { + this = default; + Visible = visible; + m_Hp = hp; + Level = level; + m_Hidden = hidden; + } + } + + private static VariableState Variable(BehaviourState state, string name) + { + foreach (var variable in state.Variables) + { + if (variable.Name == name) + { + return variable; + } + } + Assert.Fail($"{state.Behaviour} has no variable {name}."); + return null; + } + + [Test] + public void FormatValue_TurnsValuesIntoPlainData() + { + Assert.AreEqual(5, NgoCliQueries.FormatValue(5, 0)); + Assert.AreEqual("Playing", NgoCliQueries.FormatValue(CliTestPhase.Playing, 0)); + CollectionAssert.AreEqual(new[] { 1f, 2f, 3f }, (float[])NgoCliQueries.FormatValue(new Vector3(1, 2, 3), 0)); + Assert.AreEqual("hello", NgoCliQueries.FormatValue(new FixedString32Bytes("hello"), 0)); + var score = (Dictionary)NgoCliQueries.FormatValue(new CliTestScore { Points = 7, Label = "red" }, 0); + Assert.AreEqual(7, score["Points"]); + Assert.AreEqual("red", score["Label"]); + var many = new List(); + var manyById = new Dictionary(); + for (var i = 0; i < NgoCliQueries.MaxElementsShown + 5; i++) + { + many.Add(i); + manyById[i] = i; + } + // A nested collection has no count of its own, so a cut one says how much it hides. + var capped = (List)NgoCliQueries.FormatValue(many, 0); + Assert.AreEqual(NgoCliQueries.MaxElementsShown + 1, capped.Count, "Collections are capped, plus a marker."); + Assert.AreEqual(NgoCliQueries.MoreMarker(5), capped[capped.Count - 1]); + var cappedMap = (Dictionary)NgoCliQueries.FormatValue(manyById, 0); + Assert.AreEqual(NgoCliQueries.MaxElementsShown + 1, cappedMap.Count); + Assert.IsTrue(cappedMap.ContainsKey(NgoCliQueries.MoreMarker(5))); + Assert.AreEqual(NgoCliQueries.MaxElementsShown, ((List)NgoCliQueries.FormatValue(many.GetRange(0, NgoCliQueries.MaxElementsShown), 0)).Count, "A collection that fits has no marker."); + + var stats = (Dictionary)NgoCliQueries.FormatValue(new CliTestStats(1, 80, 3, 9), 0); + CollectionAssert.AreEquivalent(new[] { "Visible", "m_Hp", "Level" }, stats.Keys, "Serialized private fields count; other private fields don't."); + Assert.AreEqual(80, stats["m_Hp"]); + Assert.AreEqual(3, stats["Level"]); + + Assert.IsNull(NgoCliQueries.FormatValue(default(NetworkObjectReference), 0), "An empty reference is null."); + Assert.IsNull(NgoCliQueries.FormatValue(new NetworkObjectReference((NetworkObject)null), 0)); + Assert.IsNull(NgoCliQueries.FormatValue(new NetworkBehaviourReference(null), 0)); + Assert.IsNull(NgoCliQueries.FormatValue(null, 0)); + } + + [Test] + public void FormatTopLevel_ReturnsAStringAsAValueNotACollection() + { + var state = new VariableState(); + Assert.AreEqual("Alice", NgoCliQueries.FormatTopLevel("Alice", state, null)); + Assert.IsNull(state.Count, "A string has no element count."); + Assert.IsFalse(state.Truncated); + + var list = new VariableState(); + CollectionAssert.AreEqual(new object[] { 1, 2 }, (List)NgoCliQueries.FormatTopLevel(new List { 1, 2 }, list, null)); + Assert.AreEqual(2, list.Count, "Real collections still report their size."); + } + + /// + /// Keys that aren't simple values can share the same text (a struct or reference without ToString), so such a + /// dictionary becomes a list of {key, value} pairs instead of a map that would drop entries. + /// + [Test] + public void FormatTopLevel_DictionaryWithComplexKeys_KeepsEveryEntry() + { + var state = new VariableState(); + var byStruct = new Dictionary { { new CliTestKey { Id = 1 }, 10 }, { new CliTestKey { Id = 2 }, 20 } }; + var pairs = (List)NgoCliQueries.FormatTopLevel(byStruct, state, null); + Assert.AreEqual(2, pairs.Count, "Each entry is kept."); + Assert.AreEqual(2, state.Count); + Assert.IsFalse(state.Truncated); + var firstPair = (Dictionary)pairs[0]; + Assert.AreEqual(1, ((Dictionary)firstPair["key"])["Id"]); + Assert.AreEqual(10, firstPair["value"]); + + var byId = (Dictionary)NgoCliQueries.FormatTopLevel(new Dictionary { { 1, 3 } }, new VariableState(), null); + Assert.AreEqual(3, byId["1"], "Simple keys still make a map."); + } + + /// + /// get_object returns each owned behaviour's NetworkVariable values, nested behaviours with their child path, + /// and NetworkList contents, so they can be read without script eval. + /// + [UnityTest] + public IEnumerator RunningHost_GetObjectReturnsNetworkVariableValues() + { + UsePlayModeWithoutReload(); + var manager = CreateManager(port: GetFreeUdpPort()); + manager.NetworkConfig.EnableSceneManagement = false; + + yield return new EnterPlayMode(); + + NgoCliQueries.Start(NgoCliQueries.SessionMode.Host, null, null, -1); + var ready = NgoCliQueries.WaitReadyAsync(null, 0, 10); + yield return WaitFor(ready); + Assert.IsTrue(ready.Result.Ready, ready.Result.Reason); + + var root = new GameObject("CliStateObject"); + root.AddComponent(); + var state = root.AddComponent(); + var child = new GameObject("Lamp"); + child.transform.SetParent(root.transform); + var lamp = child.AddComponent(); + var networkObject = root.GetComponent(); + // Built at runtime, so it has no prefab id; the host is the only peer, so any id will do. + networkObject.GlobalObjectIdHash = 0x5EED; + networkObject.Spawn(); + + state.Counter.Value = 3; + state.Spot.Value = new Vector3(1, 2, 3); + state.Phase.Value = CliTestPhase.Playing; + state.Title.Value = "arena"; + state.Score.Value = new CliTestScore { Points = 7, Label = "red" }; + state.Secret.Value = 42; + state.Scores.Value = new Dictionary { { 1, 3 }, { 2, 5 } }; + state.Hits.Add(4); + state.Hits.Add(5); + lamp.Lit.Value = true; + + var id = (long)networkObject.NetworkObjectId; + var detail = NgoCliQueries.GetObject(id, null); + CollectionAssert.AreEqual(new[] { nameof(CliStateBehaviour), nameof(CliChildBehaviour) }, detail.Behaviours); + Assert.AreEqual(2, detail.State.Count); + + var rootState = detail.State[0]; + Assert.IsNull(rootState.Path, "Behaviours on the NetworkObject's own GameObject have no path."); + Assert.AreEqual(3, Variable(rootState, "Counter").Value); + Assert.AreEqual("NetworkVariable", Variable(rootState, "Counter").Type); + CollectionAssert.AreEqual(new[] { 1f, 2f, 3f }, (float[])Variable(rootState, "Spot").Value); + Assert.AreEqual("Playing", Variable(rootState, "Phase").Value); + Assert.AreEqual("arena", Variable(rootState, "Title").Value); + Assert.AreEqual(7, ((Dictionary)Variable(rootState, "Score").Value)["Points"]); + Assert.AreEqual(42, Variable(rootState, "Secret").Value, "The server reads owner-only variables."); + var hits = Variable(rootState, "Hits"); + CollectionAssert.AreEqual(new object[] { 4, 5 }, (List)hits.Value); + Assert.AreEqual(2, hits.Count); + Assert.IsFalse(hits.Truncated); + // A dictionary is a map, with its size like any other collection. + var scores = Variable(rootState, "Scores"); + CollectionAssert.AreEquivalent(new Dictionary { ["1"] = 3, ["2"] = 5 }, (Dictionary)scores.Value); + Assert.AreEqual(2, scores.Count); + Assert.IsFalse(scores.Truncated); + Assert.IsNull(Variable(rootState, "Target").Value, "An empty reference is null."); + + var childState = detail.State[1]; + Assert.AreEqual("Lamp", childState.Path); + Assert.AreEqual(true, Variable(childState, "Lit").Value); + + state.Target.Value = new NetworkBehaviourReference(lamp); + var target = (Dictionary)Variable(NgoCliQueries.GetObject(id, null, nameof(CliStateBehaviour)).State[0], "Target").Value; + Assert.AreEqual(id, target["networkObjectId"]); + Assert.AreEqual((int)lamp.NetworkBehaviourId, target["behaviourId"]); + Assert.AreEqual(nameof(CliChildBehaviour), target["behaviour"]); + Assert.AreEqual("Lamp", target["name"]); + + var filtered = NgoCliQueries.GetObject(id, null, nameof(CliChildBehaviour)); + Assert.AreEqual(nameof(CliChildBehaviour), Only(filtered.State).Behaviour); + Assert.Throws(() => NgoCliQueries.GetObject(id, null, "NoSuchBehaviour")); + Assert.IsNull(NgoCliQueries.GetObject(id, null, null, false).State, "variables false gives the short form."); + Assert.IsNull(NgoCliQueries.GetObject(id, null, nameof(CliChildBehaviour), false).State, "A filter that matches is fine in the short form."); + Assert.Throws(() => NgoCliQueries.GetObject(id, null, "NoSuchBehaviour", false), "A filter that matches nothing fails in the short form too."); + + var wire = (Dictionary)NgoCliOutput.ToWire(detail); + Assert.IsTrue(wire.ContainsKey("state")); + + networkObject.Despawn(); + NgoCliQueries.Stop(null, false); + yield return WaitForCondition(() => !manager.IsListening && !manager.ShutdownInProgress); + } + /// /// Runs a host and a second NetworkManager as its client in the same play session, and drives the commands /// that act on a remote client: start with a transport override, ownership, kick, reconnect, and a stats @@ -823,6 +1159,29 @@ public IEnumerator HostWithARemoteClient_SupportsTheClientQueries() Assert.AreEqual(2, clients.Count); Assert.IsFalse(Only(clients.FindAll(c => c.ClientId == remoteId)).IsLocal); + // References resolve on the peer being read, not NetworkManager.Singleton: an object the client doesn't + // observe has a name on the host, and only its ids on the client. + var hidden = new GameObject("CliHiddenFromClient"); + var hiddenObject = hidden.AddComponent(); + var hiddenBehaviour = hidden.AddComponent(); + hiddenObject.GlobalObjectIdHash = 0x5EED; + hiddenObject.SpawnWithObservers = false; + hiddenObject.NetworkManagerOwner = host; + hiddenObject.Spawn(); + Assert.IsFalse(client.SpawnManager.SpawnedObjects.ContainsKey(hiddenObject.NetworkObjectId), "The client doesn't observe it."); + var objectReference = new NetworkObjectReference(hiddenObject); + var behaviourReference = new NetworkBehaviourReference(hiddenBehaviour); + Assert.AreEqual("CliHiddenFromClient", ((Dictionary)NgoCliQueries.FormatValue(objectReference, 0, host))["name"]); + var onClient = (Dictionary)NgoCliQueries.FormatValue(objectReference, 0, client); + Assert.AreEqual((long)hiddenObject.NetworkObjectId, onClient["networkObjectId"]); + Assert.IsFalse(onClient.ContainsKey("name"), "The client can't resolve it."); + Assert.AreEqual(nameof(CliChildBehaviour), ((Dictionary)NgoCliQueries.FormatValue(behaviourReference, 0, host))["behaviour"]); + var behaviourOnClient = (Dictionary)NgoCliQueries.FormatValue(behaviourReference, 0, client); + Assert.AreEqual((long)hiddenObject.NetworkObjectId, behaviourOnClient["networkObjectId"], "An unresolved reference keeps its ids."); + Assert.AreEqual((int)hiddenBehaviour.NetworkBehaviourId, behaviourOnClient["behaviourId"]); + Assert.IsFalse(behaviourOnClient.ContainsKey("behaviour")); + hiddenObject.Despawn(); + var id = NgoCliQueries.Spawn("CliSpawnable", null, -1, false, "NetworkManager").Object.NetworkObjectId; var changed = NgoCliQueries.ChangeOwner(id, remoteId, "NetworkManager"); Assert.AreEqual(0, changed.PreviousOwner);