Skip to content

Commit 46c2fb3

Browse files
committed
fix missing GUID
1 parent 9460260 commit 46c2fb3

6 files changed

Lines changed: 340 additions & 5 deletions

File tree

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
#if UNITY_EDITOR
2+
using System.IO;
3+
using MenSharp;
4+
using NUnit.Framework;
5+
using UnityEditor;
6+
using UnityEditor.SceneManagement;
7+
using UnityEngine;
8+
using VRC.Udon;
9+
10+
/// The pair between a proxy and its backing UdonBehaviour has to survive a
11+
/// trip through a unitypackage: in the receiving project the program asset
12+
/// the UdonBehaviour carried is another object or missing, and the hidden
13+
/// flag may be gone. The proxy remembers its UdonBehaviour, and a program
14+
/// asset's GUID is derived from its class so the reference resolves again.
15+
public class MenSharpPairingTests
16+
{
17+
private const string Proxy = "MenSharpRuntimeSmoke";
18+
19+
[SetUp]
20+
public void SetUp()
21+
{
22+
MenSharpCompiler.CompileAll();
23+
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
24+
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
25+
}
26+
27+
private static (MenSharpBehaviour proxy, UdonBehaviour udon) Pair(GameObject target)
28+
{
29+
var proxy = (MenSharpBehaviour)target.AddComponent(MenSharpTestScene.FindType(Proxy));
30+
var pairs = MenSharpProxy.SyncPairs(target, quiet: true, undoable: false);
31+
Assert.AreEqual(1, pairs.Count);
32+
Assert.AreSame(proxy, pairs[0].proxy);
33+
return (proxy, pairs[0].udon);
34+
}
35+
36+
/// What an import from another project leaves: the UdonBehaviour is
37+
/// there, its Program Source is not, and it is not hidden either.
38+
[Test]
39+
public void AnImportedBackingBehaviourIsPairedAgainByReference()
40+
{
41+
GameObject target = new GameObject("Imported");
42+
(MenSharpBehaviour proxy, UdonBehaviour udon) = Pair(target);
43+
MenSharpProgramAsset program = MenSharpProxy.FindProgram(proxy.GetType());
44+
Assert.AreEqual(program, udon.programSource);
45+
46+
udon.programSource = null;
47+
udon.hideFlags = HideFlags.None;
48+
49+
Assert.AreSame(udon, MenSharpProxy.FindPaired(proxy));
50+
var pairs = MenSharpProxy.SyncPairs(target, quiet: true, undoable: false);
51+
Assert.AreEqual(1, pairs.Count);
52+
Assert.AreSame(udon, pairs[0].udon, "the remembered UdonBehaviour is reused, not replaced");
53+
Assert.AreEqual(program, udon.programSource);
54+
Assert.AreEqual(1, target.GetComponents<UdonBehaviour>().Length, "no second UdonBehaviour");
55+
}
56+
57+
/// The reference also wins over a stale program of another class's.
58+
[Test]
59+
public void ABackingBehaviourCarryingAnotherProgramIsRepointed()
60+
{
61+
GameObject target = new GameObject("Swapped");
62+
(MenSharpBehaviour proxy, UdonBehaviour udon) = Pair(target);
63+
MenSharpProgramAsset other = MenSharpProxy.FindProgram(MenSharpTestScene.FindType("Door"));
64+
Assert.IsNotNull(other);
65+
udon.programSource = other;
66+
67+
var pairs = MenSharpProxy.SyncPairs(target, quiet: true, undoable: false);
68+
Assert.AreSame(udon, pairs[0].udon);
69+
Assert.AreEqual(MenSharpProxy.FindProgram(proxy.GetType()), udon.programSource);
70+
Assert.AreEqual(1, target.GetComponents<UdonBehaviour>().Length);
71+
}
72+
73+
/// A proxy pasted onto another GameObject remembers the original's
74+
/// UdonBehaviour; that one belongs to the original and is left alone.
75+
[Test]
76+
public void APastedProxyDoesNotClaimAnotherObjectsBackingBehaviour()
77+
{
78+
GameObject original = new GameObject("Original");
79+
(MenSharpBehaviour proxy, UdonBehaviour udon) = Pair(original);
80+
81+
GameObject copy = new GameObject("Copy");
82+
var pasted = (MenSharpBehaviour)copy.AddComponent(MenSharpTestScene.FindType(Proxy));
83+
var serialized = new SerializedObject(pasted);
84+
serialized.FindProperty("menSharpBacking").objectReferenceValue = udon;
85+
serialized.ApplyModifiedPropertiesWithoutUndo();
86+
87+
var pairs = MenSharpProxy.SyncPairs(copy, quiet: true, undoable: false);
88+
Assert.AreEqual(1, pairs.Count);
89+
Assert.AreNotSame(udon, pairs[0].udon);
90+
Assert.AreEqual(copy, pairs[0].udon.gameObject);
91+
Assert.AreSame(udon, MenSharpProxy.FindPaired(proxy));
92+
Assert.AreSame(pairs[0].udon, MenSharpProxy.FindPaired(pasted));
93+
}
94+
95+
/// Two proxies of one class on one object, both remembering the same
96+
/// UdonBehaviour (a duplicated component): the second gets its own.
97+
[Test]
98+
public void ADuplicatedProxyGetsItsOwnBackingBehaviour()
99+
{
100+
GameObject target = new GameObject("Twice");
101+
(MenSharpBehaviour first, UdonBehaviour udon) = Pair(target);
102+
var second = (MenSharpBehaviour)target.AddComponent(MenSharpTestScene.FindType(Proxy));
103+
var serialized = new SerializedObject(second);
104+
serialized.FindProperty("menSharpBacking").objectReferenceValue = udon;
105+
serialized.ApplyModifiedPropertiesWithoutUndo();
106+
107+
var pairs = MenSharpProxy.SyncPairs(target, quiet: true, undoable: false);
108+
Assert.AreEqual(2, pairs.Count);
109+
Assert.AreSame(udon, pairs[0].udon);
110+
Assert.AreNotSame(udon, pairs[1].udon);
111+
Assert.AreEqual(2, target.GetComponents<UdonBehaviour>().Length);
112+
Assert.AreSame(pairs[1].udon, MenSharpProxy.FindPaired(second));
113+
}
114+
115+
/// A program asset created from scratch gets the GUID its class implies.
116+
[Test]
117+
public void ANewProgramAssetGetsTheGuidDerivedFromItsClass()
118+
{
119+
string uasm = Path.Combine("Library", "MenSharp", "Door.uasm");
120+
string meta = Path.Combine("Library", "MenSharp", "Door.meta.json");
121+
Assert.IsTrue(File.Exists(uasm), uasm);
122+
string folder = "Assets/MenSharp/Programs/GuidProbe";
123+
MenSharpTestScene.EnsureFolder(folder);
124+
string assetPath = folder + "/GuidProbe.Door.asset";
125+
AssetDatabase.DeleteAsset(assetPath);
126+
try
127+
{
128+
MenSharpProgramAsset asset = MenSharpImporter.CreateOrUpdate(uasm, meta, assetPath, false, out _);
129+
Assert.IsNotNull(asset);
130+
string expected = MenSharpImporter.StableGuid("GuidProbe.Door");
131+
Assert.AreEqual(expected, AssetDatabase.AssetPathToGUID(assetPath));
132+
Assert.AreEqual(asset, AssetDatabase.LoadAssetAtPath<MenSharpProgramAsset>(assetPath));
133+
Assert.IsNotNull(asset.SerializedProgramAsset, "the serialized program is made after the GUID is settled");
134+
// and an update keeps it
135+
MenSharpImporter.CreateOrUpdate(uasm, meta, assetPath, true, out _);
136+
Assert.AreEqual(expected, AssetDatabase.AssetPathToGUID(assetPath));
137+
}
138+
finally
139+
{
140+
var made = AssetDatabase.LoadAssetAtPath<MenSharpProgramAsset>(assetPath);
141+
string serializedPath = made != null && made.SerializedProgramAsset != null
142+
? AssetDatabase.GetAssetPath(made.SerializedProgramAsset)
143+
: null;
144+
AssetDatabase.DeleteAsset(assetPath);
145+
if (!string.IsNullOrEmpty(serializedPath))
146+
{
147+
AssetDatabase.DeleteAsset(serializedPath);
148+
}
149+
AssetDatabase.DeleteAsset(folder);
150+
MenSharpSources.InvalidateProgramIndex();
151+
}
152+
}
153+
}
154+
#endif

‎tests/unity-project/Assets/Tests/Editor/MenSharpPairingTests.cs.meta‎

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎unity/io.tesca.mensharp/Editor/MenSharpImporter.cs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
#if UNITY_EDITOR
1010
using System.IO;
1111
using System.Reflection;
12+
using System.Security.Cryptography;
13+
using System.Text;
14+
using System.Text.RegularExpressions;
1215
using UnityEditor;
1316
using UnityEngine;
1417
using VRC.Udon.Editor.ProgramSources;
@@ -73,6 +76,7 @@ public static MenSharpProgramAsset CreateOrUpdate(
7376
// the asset must exist on disk before its serialized program
7477
// sub-asset can be created next to it
7578
AssetDatabase.CreateAsset(programAsset, assetPath);
79+
programAsset = AdoptStableGuid(programAsset, assetPath);
7680
}
7781
CreateMilliseconds += watch.ElapsedMilliseconds;
7882
watch.Restart();
@@ -84,6 +88,70 @@ public static MenSharpProgramAsset CreateOrUpdate(
8488
return programAsset;
8589
}
8690

91+
/// The GUID a class's program asset gets when it is first created: a
92+
/// function of the class path alone, so that the same class compiles
93+
/// to the same GUID in every project. A prefab exported from one
94+
/// project then finds its programs in another as soon as that project
95+
/// has compiled — its UdonBehaviours' Program Source resolves by
96+
/// itself instead of reading `None`. (An asset that already exists
97+
/// keeps whatever GUID it has: changing it would break the references
98+
/// to it.)
99+
public static string StableGuid(string classPath)
100+
{
101+
using (var md5 = MD5.Create())
102+
{
103+
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes("MenSharp/" + classPath));
104+
var text = new StringBuilder(32);
105+
foreach (byte value in hash)
106+
{
107+
text.Append(value.ToString("x2"));
108+
}
109+
return text.ToString();
110+
}
111+
}
112+
113+
/// Rewrites a freshly created asset's `.meta` to the class's stable
114+
/// GUID and re-imports it. Nothing references the asset yet, so the
115+
/// change is safe; if some other asset already holds that GUID (one
116+
/// imported from elsewhere and moved), Unity's own GUID stays.
117+
private static MenSharpProgramAsset AdoptStableGuid(MenSharpProgramAsset asset, string assetPath)
118+
{
119+
string wanted = StableGuid(Path.GetFileNameWithoutExtension(assetPath));
120+
if (AssetDatabase.AssetPathToGUID(assetPath) == wanted)
121+
{
122+
return asset;
123+
}
124+
string holder = AssetDatabase.GUIDToAssetPath(wanted);
125+
if (!string.IsNullOrEmpty(holder) && holder != assetPath)
126+
{
127+
Debug.LogWarning(
128+
$"MenSharp: {assetPath} keeps a project-specific GUID — {holder} already has "
129+
+ "the one derived from its class. Prefabs from other projects referencing this "
130+
+ "program will need pairing again.");
131+
return asset;
132+
}
133+
string metaPath = assetPath + ".meta";
134+
if (!File.Exists(metaPath))
135+
{
136+
return asset;
137+
}
138+
string meta = File.ReadAllText(metaPath);
139+
string rewritten = Regex.Replace(
140+
meta, @"^guid: [0-9a-fA-F]{32}", "guid: " + wanted, RegexOptions.Multiline);
141+
if (rewritten == meta)
142+
{
143+
return asset;
144+
}
145+
File.WriteAllText(metaPath, rewritten);
146+
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceSynchronousImport);
147+
var reloaded = AssetDatabase.LoadAssetAtPath<MenSharpProgramAsset>(assetPath);
148+
if (AssetDatabase.AssetPathToGUID(assetPath) != wanted)
149+
{
150+
Debug.LogWarning($"MenSharp: could not give {assetPath} its stable GUID.");
151+
}
152+
return reloaded != null ? reloaded : asset;
153+
}
154+
87155
/// Where a compile's import time goes, summed over its programs.
88156
public static long LoadMilliseconds;
89157
public static long CreateMilliseconds;

‎unity/io.tesca.mensharp/Editor/MenSharpProxy.cs‎

Lines changed: 94 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,14 @@ public static UdonBehaviour FindPaired(MenSharpBehaviour proxy)
418418
{
419419
return null;
420420
}
421+
// the one it remembers, unless that now carries some other program
422+
// (the sweep will sort that out; until then the program decides)
423+
UdonBehaviour remembered = RememberedBacking(proxy);
424+
if (remembered != null
425+
&& (remembered.programSource == program || remembered.programSource == null))
426+
{
427+
return remembered;
428+
}
421429
foreach (UdonBehaviour udon in proxy.GetComponents<UdonBehaviour>())
422430
{
423431
if (udon != null && udon.programSource == program)
@@ -428,9 +436,59 @@ public static UdonBehaviour FindPaired(MenSharpBehaviour proxy)
428436
return null;
429437
}
430438

439+
private const string BackingFieldName = "menSharpBacking";
440+
441+
private static readonly FieldInfo BackingField = typeof(MenSharpBehaviour).GetField(
442+
BackingFieldName, BindingFlags.Instance | BindingFlags.NonPublic);
443+
444+
/// The UdonBehaviour a proxy remembers being paired with, when it is
445+
/// still a component of the proxy's own GameObject. A reference to
446+
/// another object's UdonBehaviour is a pasted component's leftover and
447+
/// counts for nothing.
448+
private static UdonBehaviour RememberedBacking(MenSharpBehaviour proxy)
449+
{
450+
if (BackingField == null || proxy == null)
451+
{
452+
return null;
453+
}
454+
var udon = BackingField.GetValue(proxy) as UdonBehaviour;
455+
if (udon == null || udon.gameObject != proxy.gameObject || IsStaticsHolder(udon))
456+
{
457+
return null;
458+
}
459+
return udon;
460+
}
461+
462+
/// Records the pair on the proxy — through its serialized property, so
463+
/// that a prefab instance keeps it as an override and the undo step is
464+
/// the caller's (`undoable`) or none at all.
465+
private static void RememberBacking(MenSharpBehaviour proxy, UdonBehaviour udon, bool undoable)
466+
{
467+
if (BackingField == null || (BackingField.GetValue(proxy) as UdonBehaviour) == udon)
468+
{
469+
return;
470+
}
471+
var serialized = new SerializedObject(proxy);
472+
SerializedProperty property = serialized.FindProperty(BackingFieldName);
473+
if (property == null)
474+
{
475+
return;
476+
}
477+
property.objectReferenceValue = udon;
478+
if (undoable)
479+
{
480+
serialized.ApplyModifiedProperties();
481+
}
482+
else
483+
{
484+
serialized.ApplyModifiedPropertiesWithoutUndo();
485+
}
486+
}
487+
431488
/// Is this an UdonBehaviour *we* placed? Only ones carrying a MenSharp
432489
/// program qualify, so hand-authored Udon (graphs, UdonSharp) is never
433-
/// touched — least of all removed.
490+
/// touched — least of all removed. (One a proxy remembers is ours too,
491+
/// whatever it carries: see `SyncPairs`.)
434492
private static bool IsBackingBehaviour(UdonBehaviour udon)
435493
{
436494
if (udon == null || IsStaticsHolder(udon))
@@ -473,16 +531,29 @@ private static bool IsBackingBehaviour(UdonBehaviour udon)
473531
return pairs;
474532
}
475533

534+
// what the proxies remember is ours even when nothing else says so:
535+
// imported from another project, the program asset it carried is
536+
// gone and the hidden flag may be too (saved with Reveal on)
537+
MenSharpBehaviour[] proxies = target.GetComponents<MenSharpBehaviour>();
538+
var remembered = new HashSet<UdonBehaviour>();
539+
foreach (MenSharpBehaviour proxy in proxies)
540+
{
541+
UdonBehaviour udon = RememberedBacking(proxy);
542+
if (udon != null)
543+
{
544+
remembered.Add(udon);
545+
}
546+
}
476547
var spare = new List<UdonBehaviour>();
477548
foreach (UdonBehaviour udon in target.GetComponents<UdonBehaviour>())
478549
{
479-
if (IsBackingBehaviour(udon))
550+
if (IsBackingBehaviour(udon) || remembered.Contains(udon))
480551
{
481552
spare.Add(udon);
482553
}
483554
}
484555

485-
foreach (MenSharpBehaviour proxy in target.GetComponents<MenSharpBehaviour>())
556+
foreach (MenSharpBehaviour proxy in proxies)
486557
{
487558
MenSharpProgramAsset program = FindProgram(proxy.GetType());
488559
if (program == null)
@@ -498,7 +569,25 @@ private static bool IsBackingBehaviour(UdonBehaviour udon)
498569
}
499570

500571
UdonBehaviour paired = null;
501-
for (int index = 0; index < spare.Count; index++)
572+
// the remembered one first, whatever it carries now — the
573+
// component uGUI events and other scripts point at — re-pointed
574+
// at the current program. Still in `spare` means no earlier
575+
// proxy (a pasted copy remembering the same one) claimed it
576+
UdonBehaviour kept = RememberedBacking(proxy);
577+
if (kept != null && spare.Remove(kept))
578+
{
579+
paired = kept;
580+
if (paired.programSource != program)
581+
{
582+
if (undoable)
583+
{
584+
Undo.RecordObject(paired, "Pair MenSharp behaviour");
585+
}
586+
paired.programSource = program;
587+
EditorUtility.SetDirty(paired);
588+
}
589+
}
590+
for (int index = 0; paired == null && index < spare.Count; index++)
502591
{
503592
if (spare[index].programSource == program)
504593
{
@@ -539,6 +628,7 @@ private static bool IsBackingBehaviour(UdonBehaviour udon)
539628
ApplyVisibility(paired);
540629
ApplySyncMode(paired, program);
541630
ApplySerializedProgram(paired, program);
631+
RememberBacking(proxy, paired, undoable);
542632
pairs.Add((proxy, paired));
543633
}
544634

0 commit comments

Comments
 (0)