@scenoco-three/unity 0.9.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@ using UnityEditor.SceneManagement;
14
14
  using UnityEngine;
15
15
  using UnityEngine.Rendering;
16
16
  using UnityEngine.SceneManagement;
17
+ using UnityEngine.UIElements;
17
18
  using Object = UnityEngine.Object;
18
19
 
19
20
  namespace SceNoCo
@@ -38,6 +39,9 @@ namespace SceNoCo
38
39
  }
39
40
 
40
41
  static readonly List<string> warnings = new List<string>();
42
+ /// <summary>What the last import could not carry across, each with where it was written.</summary>
43
+ public static IReadOnlyList<string> Warnings => warnings;
44
+ static Dictionary<string, object> ui;
41
45
 
42
46
  [MenuItem("SceNoCo/Import")]
43
47
  public static void Import()
@@ -51,6 +55,10 @@ namespace SceNoCo
51
55
  AssetDatabase.Refresh();
52
56
  var data = (Dictionary<string, object>)Json.Parse(File.ReadAllText(DataPath));
53
57
  foreach (var w in List(data["warnings"])) warnings.Add((string)w);
58
+ ui = data.TryGetValue("ui", out var u) ? Obj(u) : null;
59
+ Try(Project.Recommended, "rendering settings");
60
+ if (data.TryGetValue("layers", out var layers)) Try(() => Project.Layers(Obj(layers)), "layers");
61
+ if (data.TryGetValue("input", out var input)) Try(() => Project.Input((string)input), "input actions");
54
62
 
55
63
  foreach (var m in List(data["meshes"])) Try(() => MakeMesh(Obj(m)), Str(Obj(m), "path"));
56
64
  foreach (var m in List(data["materials"])) Try(() => MakeMaterial(Obj(m)), Str(Obj(m), "path"));
@@ -62,11 +70,16 @@ namespace SceNoCo
62
70
  foreach (var p in prefabs) Try(() => WirePrefab(p), Str(p, "path"));
63
71
 
64
72
  var scenes = List(data["scenes"]).Select(Obj).ToList();
65
- replaced = false;
66
- foreach (var s in scenes) Try(() => SaveScene(s), Str(s, "path"));
73
+ reopen = null;
74
+ for (var i = 0; i < scenes.Count; i++)
75
+ {
76
+ var s = scenes[i];
77
+ var first = i == 0;
78
+ Try(() => SaveScene(s, first), Str(s, "path"));
79
+ }
67
80
  var paths = scenes.Select(s => Str(s, "path")).ToList();
68
- // An empty untitled scene stood in for the first exported one: open it in its place.
69
- if (replaced && paths.Count > 0) EditorSceneManager.OpenScene(paths[0], OpenSceneMode.Single);
81
+ // An empty untitled scene stood in for the first exported one, or an open scene was rebuilt: open it again.
82
+ if (reopen != null && paths.Count > 0) EditorSceneManager.OpenScene(reopen == "" ? paths[0] : reopen, OpenSceneMode.Single);
70
83
  EditorBuildSettings.scenes = paths.Select(p => new EditorBuildSettingsScene(p, true))
71
84
  .Concat(EditorBuildSettings.scenes.Where(s => !paths.Contains(s.path))).ToArray();
72
85
 
@@ -157,6 +170,18 @@ namespace SceNoCo
157
170
  if (t != null) mat.SetTexture("_BaseMap", t);
158
171
  else warnings.Add($"{path}: texture {tex} did not import.");
159
172
  }
173
+ if (m.TryGetValue("emissionTexture", out var etex))
174
+ {
175
+ var t = AssetDatabase.LoadAssetAtPath<Texture2D>((string)etex);
176
+ if (t != null) mat.SetTexture("_EmissionMap", t);
177
+ else warnings.Add($"{path}: emission texture {etex} did not import.");
178
+ }
179
+ if (m.TryGetValue("tiling", out var tiling))
180
+ {
181
+ var f = Floats(tiling);
182
+ mat.SetTextureScale("_BaseMap", new Vector2(f[0], f[1]));
183
+ mat.SetTextureScale("_EmissionMap", new Vector2(f[0], f[1]));
184
+ }
160
185
 
161
186
  mat.SetFloat("_Cull", Num(m, "cull", 2));
162
187
  var transparent = m.TryGetValue("transparent", out var tr) && (bool)tr;
@@ -219,19 +244,26 @@ namespace SceNoCo
219
244
  finally { PrefabUtility.UnloadPrefabContents(root); }
220
245
  }
221
246
 
222
- static bool replaced;
247
+ /// <summary>The scene to open once the import is done: "" for the first exported one.</summary>
248
+ static string reopen;
223
249
 
224
- static void SaveScene(Dictionary<string, object> s)
250
+ static void SaveScene(Dictionary<string, object> s, bool first)
225
251
  {
226
252
  var path = Str(s, "path");
227
253
  Folder(Path.GetDirectoryName(path));
228
254
  // A scene of its own, beside whatever is open: nothing the user has open is touched. Unity
229
- // cannot add one beside an untitled scene, so an untouched untitled one is replaced instead.
255
+ // cannot add one beside an untitled scene, nor save over an open one, so an untouched untitled
256
+ // scene or this very scene open is replaced instead, and opened again at the end.
257
+ var open = SceneManager.GetSceneByPath(path);
258
+ if (open.IsValid() && open.isDirty) throw new Exception("it is open with unsaved changes — save or discard them, then import again");
259
+ var beside = open.IsValid() && SceneManager.sceneCount > 1;
260
+ if (beside) EditorSceneManager.CloseScene(open, true);
230
261
  var previous = SceneManager.GetActiveScene();
231
262
  var untitled = SceneManager.sceneCount == 1 && string.IsNullOrEmpty(previous.path);
232
263
  if (untitled && previous.isDirty) throw new Exception("the open scene is untitled and has unsaved changes — save or discard it, then import again");
233
- var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, untitled ? NewSceneMode.Single : NewSceneMode.Additive);
234
- if (untitled) { replaced = true; previous = default; }
264
+ var single = untitled || previous.path == path;
265
+ var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, single ? NewSceneMode.Single : NewSceneMode.Additive);
266
+ if (single) { reopen ??= untitled ? "" : path; previous = default; }
235
267
  SceneManager.SetActiveScene(scene);
236
268
  try
237
269
  {
@@ -243,6 +275,7 @@ namespace SceNoCo
243
275
  for (var i = 0; i < roots.Count; i++) Wire(roots[i], built[i], holder);
244
276
  foreach (var go in built) go.transform.SetParent(null, false);
245
277
  Object.DestroyImmediate(holder);
278
+ if (first) MakeInput();
246
279
 
247
280
  RenderSettings.skybox = null;
248
281
  Color background = Color.black;
@@ -253,6 +286,7 @@ namespace SceNoCo
253
286
  {
254
287
  cam.clearFlags = hasBackground ? CameraClearFlags.SolidColor : cam.clearFlags;
255
288
  cam.backgroundColor = background;
289
+ Volumes.Enable(cam);
256
290
  }
257
291
  if (cameras.Count > 0) cameras[0].gameObject.tag = "MainCamera";
258
292
  else warnings.Add($"{path}: no camera in the scene.");
@@ -290,6 +324,10 @@ namespace SceNoCo
290
324
  RenderSettings.ambientMode = AmbientMode.Flat;
291
325
  RenderSettings.ambientLight = Color.black;
292
326
  }
327
+ // three lights a surface with no environment by nothing but its lights: no skybox reflections either.
328
+ RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom;
329
+ RenderSettings.customReflectionTexture = null;
330
+ RenderSettings.reflectionIntensity = s.ContainsKey("environment") ? 1 : 0;
293
331
  EditorSceneManager.SaveScene(scene, path);
294
332
  }
295
333
  finally
@@ -298,6 +336,7 @@ namespace SceNoCo
298
336
  {
299
337
  SceneManager.SetActiveScene(previous);
300
338
  EditorSceneManager.CloseScene(scene, true);
339
+ if (beside) EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
301
340
  }
302
341
  }
303
342
  }
@@ -319,6 +358,7 @@ namespace SceNoCo
319
358
  var r = Floats(n["rotation"]);
320
359
  go.transform.localRotation = new Quaternion(r[0], r[1], r[2], r[3]);
321
360
  go.transform.localScale = V3(n["scale"]);
361
+ if (n.TryGetValue("layer", out var layer)) go.layer = Convert.ToInt32(layer, CultureInfo.InvariantCulture);
322
362
 
323
363
  if (n.TryGetValue("mesh", out var mesh))
324
364
  {
@@ -341,6 +381,9 @@ namespace SceNoCo
341
381
  if (t == null) warnings.Add($"{Where(comp, n)}: no MonoBehaviour named {type} — it has a stub in Assets/Scripts unless a class of that name exists elsewhere.");
342
382
  else go.AddComponent(t);
343
383
  }
384
+ else if (type == "ParticleSystem") Particles.Add(go, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"));
385
+ else if (type == "UIDocument") MakeDocument(go, Obj(comp["fields"]), Where(comp, n));
386
+ else if (Volumes.Add(go, type, Obj(comp["fields"]))) { }
344
387
  else if (!Physics.Add(go, type, Obj(comp["fields"]))) warnings.Add($"{Where(comp, n)}: {type} has no Unity counterpart here — left off.");
345
388
  }
346
389
 
@@ -351,6 +394,122 @@ namespace SceNoCo
351
394
  return go;
352
395
  }
353
396
 
397
+ /// <summary>
398
+ /// A game's post effects as a URP Volume and its profile, one per node that has them. By type name and
399
+ /// serialized field, as the project's settings are, so a project without URP still compiles this.
400
+ /// </summary>
401
+ static class Volumes
402
+ {
403
+ const string Rendering = "UnityEngine.Rendering.{0}, Unity.RenderPipelines.Core.Runtime";
404
+ const string Universal = "UnityEngine.Rendering.Universal.{0}, Unity.RenderPipelines.Universal.Runtime";
405
+ static readonly Dictionary<GameObject, ScriptableObject> Profiles = new Dictionary<GameObject, ScriptableObject>();
406
+ static readonly HashSet<string> Written = new HashSet<string>();
407
+ static readonly string[] Effects = { "Bloom", "Tonemapping", "ColorAdjustments", "Vignette", "DepthOfField", "ChromaticAberration", "FilmGrain" };
408
+
409
+ public static bool Add(GameObject go, string type, Dictionary<string, object> f)
410
+ {
411
+ if (type == "Volume")
412
+ {
413
+ Profile(go);
414
+ var volume = new SerializedObject(go.GetComponent(Type.GetType(string.Format(Rendering, "Volume"))));
415
+ volume.FindProperty("priority").floatValue = Num(f, "priority", 0);
416
+ volume.ApplyModifiedPropertiesWithoutUndo();
417
+ return true;
418
+ }
419
+ if (!Effects.Contains(type)) return false;
420
+ var effect = Type.GetType(string.Format(Universal, type));
421
+ if (effect == null) return false;
422
+ var profile = Profile(go);
423
+ var added = (ScriptableObject)profile.GetType().GetMethod("Add", new[] { typeof(Type), typeof(bool) }).Invoke(profile, new object[] { effect, false });
424
+ var o = new SerializedObject(added);
425
+ void Float(string name, float value) => Set(o, name, p => p.floatValue = value);
426
+ void Tint(string name, string field, string fallback) => Set(o, name, p => p.colorValue = f.TryGetValue(field, out var c) ? Hex((string)Obj(c)["color"]) : Hex(fallback));
427
+ switch (type)
428
+ {
429
+ case "Bloom":
430
+ Float("threshold", Num(f, "threshold", 0.9f));
431
+ Float("intensity", Num(f, "intensity", 1));
432
+ Float("scatter", Num(f, "scatter", 0.7f));
433
+ Tint("tint", "tint", "#ffffff");
434
+ break;
435
+ case "Tonemapping":
436
+ var mode = f.TryGetValue("mode", out var m) ? (string)m : "ACES";
437
+ Set(o, "mode", p => p.enumValueIndex = mode == "ACES" ? 2 : mode == "Neutral" ? 1 : 0);
438
+ break;
439
+ case "ColorAdjustments":
440
+ Float("postExposure", Num(f, "postExposure", 0));
441
+ Float("contrast", Num(f, "contrast", 0));
442
+ Float("hueShift", Num(f, "hueShift", 0));
443
+ Float("saturation", Num(f, "saturation", 0));
444
+ Tint("colorFilter", "colorFilter", "#ffffff");
445
+ break;
446
+ case "Vignette":
447
+ Float("intensity", Num(f, "intensity", 0.3f));
448
+ Float("smoothness", Num(f, "smoothness", 0.2f));
449
+ Tint("color", "color", "#000000");
450
+ if (f.TryGetValue("center", out var c))
451
+ {
452
+ var at = Floats(Obj(c)["v2"]);
453
+ Set(o, "center", p => p.vector2Value = new Vector2(at[0], at[1]));
454
+ }
455
+ break;
456
+ case "DepthOfField":
457
+ Set(o, "mode", p => p.enumValueIndex = 2); // Bokeh
458
+ Float("focusDistance", Num(f, "focusDistance", 10));
459
+ Float("focalLength", Num(f, "focalLength", 50));
460
+ Float("aperture", Num(f, "aperture", 5.6f));
461
+ break;
462
+ default:
463
+ Float("intensity", Num(f, "intensity", 0.3f));
464
+ break;
465
+ }
466
+ o.ApplyModifiedPropertiesWithoutUndo();
467
+ // Each is an object of its own in the profile's file, and its list is lost at save unless marked.
468
+ AssetDatabase.AddObjectToAsset(added, profile);
469
+ EditorUtility.SetDirty(added);
470
+ EditorUtility.SetDirty(profile);
471
+ return true;
472
+ }
473
+
474
+ /// <summary>Post Processing on for a camera, in a game with a Volume in any scene: one kept across loads shapes every level's camera.</summary>
475
+ public static void Enable(Camera camera)
476
+ {
477
+ if (Profiles.Count == 0 && !File.ReadAllText(DataPath).Contains("\"Volume\"")) return;
478
+ var data = Type.GetType(string.Format(Universal, "UniversalAdditionalCameraData"));
479
+ if (data == null) return;
480
+ var extra = camera.GetComponent(data) ?? camera.gameObject.AddComponent(data);
481
+ var o = new SerializedObject(extra);
482
+ o.FindProperty("m_RenderPostProcessing").boolValue = true;
483
+ o.ApplyModifiedPropertiesWithoutUndo();
484
+ }
485
+
486
+ static ScriptableObject Profile(GameObject go)
487
+ {
488
+ if (Profiles.TryGetValue(go, out var made)) return made;
489
+ var profileType = Type.GetType(string.Format(Rendering, "VolumeProfile"));
490
+ var path = $"Assets/Materials/Volume-{go.name}.asset";
491
+ for (var i = 2; !Written.Add(path); i++) path = $"Assets/Materials/Volume-{go.name}-{i}.asset";
492
+ Directory.CreateDirectory("Assets/Materials");
493
+ AssetDatabase.DeleteAsset(path);
494
+ var profile = ScriptableObject.CreateInstance(profileType);
495
+ AssetDatabase.CreateAsset(profile, path);
496
+ var volume = go.GetComponent(Type.GetType(string.Format(Rendering, "Volume"))) ?? go.AddComponent(Type.GetType(string.Format(Rendering, "Volume")));
497
+ var o = new SerializedObject(volume);
498
+ o.FindProperty("sharedProfile").objectReferenceValue = profile;
499
+ o.FindProperty("m_IsGlobal").boolValue = true;
500
+ o.ApplyModifiedPropertiesWithoutUndo();
501
+ Profiles[go] = profile;
502
+ return profile;
503
+ }
504
+
505
+ static void Set(SerializedObject o, string name, Action<SerializedProperty> value)
506
+ {
507
+ var parameter = o.FindProperty(name);
508
+ parameter.FindPropertyRelative("m_OverrideState").boolValue = true;
509
+ value(parameter.FindPropertyRelative("m_Value"));
510
+ }
511
+ }
512
+
354
513
  /** Set the fields of a node's game components, walking the data and the built objects together. */
355
514
  static void Wire(Dictionary<string, object> n, GameObject go, GameObject root)
356
515
  {
@@ -437,6 +596,51 @@ namespace SceNoCo
437
596
  return t != null ? go.GetComponent(t) : go.GetComponent(wanted);
438
597
  }
439
598
 
599
+ // --- the page and input ------------------------------------------------------------------
600
+
601
+ /// <summary>A UIDocument for the page's element: its UXML, and Panel Settings that scale as core's UIDocument does.</summary>
602
+ static void MakeDocument(GameObject go, Dictionary<string, object> f, string where)
603
+ {
604
+ var element = f.TryGetValue("element", out var e) ? (string)e : "ui";
605
+ var documents = ui != null && ui.TryGetValue("documents", out var d) ? Obj(d) : new Dictionary<string, object>();
606
+ if (!documents.TryGetValue(element, out var uxml))
607
+ {
608
+ warnings.Add($"{where}: no UXML for the element \"{element}\" — the page has no element with that id.");
609
+ return;
610
+ }
611
+ var path = $"Assets/UI/{element}.panel.asset";
612
+ var panel = AssetDatabase.LoadAssetAtPath<PanelSettings>(path);
613
+ if (panel == null)
614
+ {
615
+ panel = ScriptableObject.CreateInstance<PanelSettings>();
616
+ SaveAsset(panel, path);
617
+ }
618
+ panel.themeStyleSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(Str(ui, "theme"));
619
+ panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
620
+ panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
621
+ var size = f.TryGetValue("referenceResolution", out var r) ? Floats(Obj(r)["v2"]) : new[] { 1280f, 720f };
622
+ panel.referenceResolution = new Vector2Int(Mathf.RoundToInt(size[0]), Mathf.RoundToInt(size[1]));
623
+ panel.match = Num(f, "match", 0.5f);
624
+ // In the page's order: an element written later draws over an earlier one.
625
+ panel.sortingOrder = documents.Keys.ToList().IndexOf(element);
626
+ EditorUtility.SetDirty(panel);
627
+ var doc = go.AddComponent<UIDocument>();
628
+ doc.panelSettings = panel;
629
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>((string)uxml);
630
+ }
631
+
632
+ /// <summary>The first scene's Input object: the UI's EventSystem and its Input System module, kept for the whole game.</summary>
633
+ static void MakeInput()
634
+ {
635
+ var go = new GameObject("Input");
636
+ foreach (var name in new[] { "UnityEngine.EventSystems.EventSystem, UnityEngine.UI", "UnityEngine.InputSystem.UI.InputSystemUIInputModule, Unity.InputSystem", "SceNoCo.KeepAcrossScenes, Assembly-CSharp" })
637
+ {
638
+ var t = Type.GetType(name);
639
+ if (t != null) go.AddComponent(t);
640
+ else warnings.Add($"Input: {name.Split(',')[0]} is not in this project — add the Input System and UI packages.");
641
+ }
642
+ }
643
+
440
644
  static GameObject Find(GameObject root, string path)
441
645
  {
442
646
  var t = root.transform;
@@ -477,10 +681,8 @@ namespace SceNoCo
477
681
  static Type GameType(string name)
478
682
  {
479
683
  if (types.TryGetValue(name, out var known)) return known;
480
- var found = AppDomain.CurrentDomain.GetAssemblies()
481
- .Where(a => !a.FullName.StartsWith("Unity") && !a.FullName.StartsWith("System") && !a.FullName.StartsWith("mscorlib"))
482
- .SelectMany(a => { try { return a.GetTypes(); } catch { return new Type[0]; } })
483
- .FirstOrDefault(t => t.Name == name && typeof(MonoBehaviour).IsAssignableFrom(t));
684
+ var found = TypeCache.GetTypesDerivedFrom<MonoBehaviour>()
685
+ .FirstOrDefault(t => t.Name == name && !t.Assembly.FullName.StartsWith("Unity"));
484
686
  types[name] = found;
485
687
  return found;
486
688
  }
@@ -490,6 +692,231 @@ namespace SceNoCo
490
692
 
491
693
  // --- physics: SceNoCo's rapier and box2d components are Unity's own --------------------
492
694
 
695
+ /// <summary>The project's own settings: what a three.js game draws and reads like, in Unity 6.</summary>
696
+ static class Project
697
+ {
698
+ /// <summary>
699
+ /// three.js renders in linear space to an sRGB canvas, with no tone mapping, no antialiasing (SceNoCo's
700
+ /// default), no light limit per object and no environment: Linear colour space, HDR kept for a bloom a
701
+ /// game adds, MSAA off, render scale 1, Forward+, soft shadows. Applied to every URP asset in the
702
+ /// project, through their serialized fields, so a project without URP still compiles this.
703
+ /// </summary>
704
+ public static void Recommended()
705
+ {
706
+ PlayerSettings.colorSpace = ColorSpace.Linear;
707
+ foreach (var guid in AssetDatabase.FindAssets("t:UniversalRenderPipelineAsset"))
708
+ {
709
+ var asset = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid));
710
+ var so = new SerializedObject(asset);
711
+ Set(so, "m_SupportsHDR", p => p.boolValue = true);
712
+ Set(so, "m_MSAA", p => p.intValue = 1);
713
+ Set(so, "m_RenderScale", p => p.floatValue = 1);
714
+ Set(so, "m_SoftShadowsSupported", p => p.boolValue = true);
715
+ so.ApplyModifiedPropertiesWithoutUndo();
716
+ }
717
+ foreach (var guid in AssetDatabase.FindAssets("t:UniversalRendererData"))
718
+ {
719
+ var so = new SerializedObject(AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)));
720
+ // Forward+: no cap of eight lights per object — three has none.
721
+ Set(so, "m_RenderingMode", p => p.intValue = 2);
722
+ so.ApplyModifiedPropertiesWithoutUndo();
723
+ }
724
+ }
725
+
726
+ static void Set(SerializedObject so, string name, Action<SerializedProperty> set)
727
+ {
728
+ var p = so.FindProperty(name);
729
+ if (p != null) set(p);
730
+ }
731
+
732
+ /// <summary>The game's layers by name, and the pairs its physics lets pass through each other.</summary>
733
+ public static void Layers(Dictionary<string, object> l)
734
+ {
735
+ var tags = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
736
+ var names = tags.FindProperty("layers");
737
+ foreach (var pair in Obj(l["names"]))
738
+ {
739
+ var index = int.Parse(pair.Key, CultureInfo.InvariantCulture);
740
+ var current = names.GetArrayElementAtIndex(index).stringValue;
741
+ if (string.IsNullOrEmpty(current) || current.StartsWith("Layer ")) names.GetArrayElementAtIndex(index).stringValue = (string)pair.Value;
742
+ else if (current != (string)pair.Value) warnings.Add($"layers: Unity layer {index} is \"{current}\" already — the game's {pair.Value} shares it.");
743
+ }
744
+ tags.ApplyModifiedPropertiesWithoutUndo();
745
+ Matrix("ProjectSettings/Physics2DSettings.asset", List(l["ignore2D"]).Select(Floats));
746
+ Matrix("ProjectSettings/DynamicsManager.asset", List(l["ignore3D"]).Select(Floats));
747
+ }
748
+
749
+ /// <summary>
750
+ /// The pairs written into the project's collision matrix itself: IgnoreLayerCollision called in the
751
+ /// Editor lasts only until the settings reload. A row's bit set is "collides".
752
+ /// </summary>
753
+ static void Matrix(string settings, IEnumerable<float[]> pairs)
754
+ {
755
+ var so = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(settings)[0]);
756
+ var rows = so.FindProperty("m_LayerCollisionMatrix");
757
+ if (rows == null) return;
758
+ foreach (var pair in pairs)
759
+ {
760
+ int a = (int)pair[0], b = (int)pair[1];
761
+ rows.GetArrayElementAtIndex(a).longValue &= ~(1L << b);
762
+ rows.GetArrayElementAtIndex(b).longValue &= ~(1L << a);
763
+ }
764
+ so.ApplyModifiedPropertiesWithoutUndo();
765
+ }
766
+
767
+ /// <summary>SceNoCo's named axes and buttons as the project-wide actions: `InputSystem.actions["Horizontal"]`.</summary>
768
+ public static void Input(string path)
769
+ {
770
+ AssetDatabase.ImportAsset(path);
771
+ var asset = AssetDatabase.LoadMainAssetAtPath(path);
772
+ var system = Type.GetType("UnityEngine.InputSystem.InputSystem, Unity.InputSystem");
773
+ var actions = system?.GetProperty("actions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
774
+ if (asset == null || actions == null || !actions.CanWrite)
775
+ {
776
+ warnings.Add($"input: {path} is not the project-wide actions — set it in Project Settings ▸ Input System Package.");
777
+ return;
778
+ }
779
+ actions.SetValue(null, asset);
780
+ }
781
+ }
782
+
783
+ /// <summary>
784
+ /// A SceNoCo ParticleSystem's effect — Shuriken's modules under Shuriken's names — as Unity's own
785
+ /// ParticleSystem. three.quarks emits along +Z like Unity; the mirror on Z turns a cone or a hemisphere round.
786
+ /// </summary>
787
+ static class Particles
788
+ {
789
+ public static void Add(GameObject go, Dictionary<string, object> f, Action<string> warn)
790
+ {
791
+ if (!f.TryGetValue("effect", out var e) || !(e is Dictionary<string, object> eo) || !eo.ContainsKey("object"))
792
+ {
793
+ warn("ParticleSystem has no effect it could read — left off.");
794
+ return;
795
+ }
796
+ var c = Fields(eo);
797
+ var ps = go.AddComponent<ParticleSystem>();
798
+ ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
799
+ var main = ps.main;
800
+ main.duration = Num(c, "duration", 5);
801
+ main.loop = Bool(c, "looping", true);
802
+ main.prewarm = Bool(c, "prewarm", false);
803
+ main.startLifetime = Num(c, "startLifetime", 5);
804
+ main.startSpeed = Num(c, "startSpeed", 5);
805
+ main.startSize = Num(c, "startSize", 1);
806
+ main.startRotation = Num(c, "startRotation", 0) * Mathf.Deg2Rad;
807
+ main.startColor = ColorOf(c, "startColor", Color.white);
808
+ main.gravityModifier = Num(c, "gravityModifier", 0);
809
+ main.simulationSpace = Str(c, "simulationSpace") == "World" ? ParticleSystemSimulationSpace.World : ParticleSystemSimulationSpace.Local;
810
+ main.playOnAwake = !f.TryGetValue("playOnAwake", out var awake) || (bool)awake;
811
+ main.scalingMode = ParticleSystemScalingMode.Hierarchy;
812
+
813
+ var emission = ps.emission;
814
+ var em = Sub(c, "emission");
815
+ emission.rateOverTime = Num(em, "rateOverTime", 10);
816
+ if (em.TryGetValue("bursts", out var bursts))
817
+ emission.SetBursts(List(Obj(bursts)["array"]).Select(b => Fields(Obj(b))).Select(b => new ParticleSystem.Burst(Num(b, "time", 0), (short)Num(b, "count", 0))).ToArray());
818
+
819
+ var shape = ps.shape;
820
+ var sh = Sub(c, "shape");
821
+ var type = sh.ContainsKey("type") ? Str(sh, "type") : "Cone";
822
+ shape.radius = Num(sh, "radius", 1);
823
+ shape.angle = Num(sh, "angle", 25);
824
+ shape.arc = Num(sh, "arc", 360);
825
+ switch (type)
826
+ {
827
+ case "Sphere": shape.shapeType = ParticleSystemShapeType.Sphere; break;
828
+ case "Hemisphere": shape.shapeType = ParticleSystemShapeType.Hemisphere; shape.rotation = new Vector3(0, 180, 0); break;
829
+ case "Circle": shape.shapeType = ParticleSystemShapeType.Circle; break;
830
+ case "Donut": shape.shapeType = ParticleSystemShapeType.Donut; break;
831
+ case "Rectangle": shape.shapeType = ParticleSystemShapeType.Rectangle; shape.scale = new Vector3(shape.radius * 2, shape.radius * 2, 1); break;
832
+ case "Point": shape.shapeType = ParticleSystemShapeType.Sphere; shape.radius = 0.0001f; break;
833
+ default: shape.shapeType = ParticleSystemShapeType.Cone; shape.rotation = new Vector3(0, 180, 0); break;
834
+ }
835
+
836
+ if (c.TryGetValue("noise", out _))
837
+ {
838
+ var n = Sub(c, "noise");
839
+ var noise = ps.noise;
840
+ noise.enabled = true;
841
+ noise.strength = Num(n, "strength", 1);
842
+ noise.frequency = Num(n, "frequency", 2);
843
+ }
844
+ if (c.TryGetValue("colorOverLifetime", out _))
845
+ {
846
+ var colors = List(Obj(Sub(c, "colorOverLifetime")["colors"])["array"]).Select(x => Hex(Str(Obj(x), "color"))).ToArray();
847
+ if (colors.Length > 0)
848
+ {
849
+ // Evenly spaced, as the effect writes them; full alpha, fading out over the last third, as three.quarks does.
850
+ var keys = colors.Select((col, i) => new GradientColorKey(col, colors.Length == 1 ? 0 : i / (float)(colors.Length - 1))).Take(8).ToArray();
851
+ var gradient = new Gradient();
852
+ gradient.SetKeys(keys, new[] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 0.7f), new GradientAlphaKey(0, 1) });
853
+ var col = ps.colorOverLifetime;
854
+ col.enabled = true;
855
+ col.color = gradient;
856
+ }
857
+ }
858
+ if (c.TryGetValue("sizeOverLifetime", out _))
859
+ {
860
+ var values = Floats(Obj(Sub(c, "sizeOverLifetime")["curve"])["array"]);
861
+ if (values.Length > 0)
862
+ {
863
+ var curve = new AnimationCurve(values.Select((v, i) => new Keyframe(values.Length == 1 ? 0 : i / (float)(values.Length - 1), v)).ToArray());
864
+ for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
865
+ for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
866
+ var size = ps.sizeOverLifetime;
867
+ size.enabled = true;
868
+ size.size = new ParticleSystem.MinMaxCurve(1, curve);
869
+ }
870
+ }
871
+ if (c.TryGetValue("rotationOverLifetime", out _))
872
+ {
873
+ var rot = ps.rotationOverLifetime;
874
+ rot.enabled = true;
875
+ rot.z = Num(Sub(c, "rotationOverLifetime"), "angularVelocity", 0) * Mathf.Deg2Rad;
876
+ }
877
+
878
+ var r = Sub(c, "renderer");
879
+ var renderer = go.GetComponent<ParticleSystemRenderer>();
880
+ renderer.renderMode = Str(r, "renderMode") switch
881
+ {
882
+ "StretchedBillboard" => ParticleSystemRenderMode.Stretch,
883
+ "HorizontalBillboard" => ParticleSystemRenderMode.HorizontalBillboard,
884
+ "VerticalBillboard" => ParticleSystemRenderMode.VerticalBillboard,
885
+ "Mesh" => ParticleSystemRenderMode.Mesh,
886
+ _ => ParticleSystemRenderMode.Billboard,
887
+ };
888
+ renderer.sharedMaterial = SharedMaterial(Str(r, "blending") == "Alpha" ? "Alpha" : "Additive");
889
+ }
890
+
891
+ /// <summary>One material per blending, shared by every system: URP's particle shader, Unity's soft round sprite.</summary>
892
+ static Material SharedMaterial(string blending)
893
+ {
894
+ var path = $"Assets/Materials/Particles-{blending}.mat";
895
+ var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
896
+ if (mat != null) return mat;
897
+ var shader = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit");
898
+ mat = new Material(shader);
899
+ mat.SetTexture("_BaseMap", AssetDatabase.GetBuiltinExtraResource<Texture2D>("Default-Particle.psd"));
900
+ mat.SetFloat("_Surface", 1);
901
+ mat.SetFloat("_Blend", blending == "Additive" ? 2 : 0);
902
+ mat.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha);
903
+ mat.SetFloat("_DstBlend", (float)(blending == "Additive" ? BlendMode.One : BlendMode.OneMinusSrcAlpha));
904
+ mat.SetFloat("_ZWrite", 0);
905
+ mat.SetOverrideTag("RenderType", "Transparent");
906
+ mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
907
+ mat.renderQueue = (int)RenderQueue.Transparent;
908
+ SaveAsset(mat, path);
909
+ return mat;
910
+ }
911
+
912
+ static Dictionary<string, object> Fields(Dictionary<string, object> o) => Obj(Obj(o["object"])["fields"]);
913
+ static Dictionary<string, object> Sub(Dictionary<string, object> c, string key) =>
914
+ c.TryGetValue(key, out var v) && v is Dictionary<string, object> d && d.ContainsKey("object") ? Fields(d) : new Dictionary<string, object>();
915
+ static bool Bool(Dictionary<string, object> d, string key, bool fallback) => d.TryGetValue(key, out var v) && v is bool b ? b : fallback;
916
+ static Color ColorOf(Dictionary<string, object> d, string key, Color fallback) =>
917
+ d.TryGetValue(key, out var v) && v is Dictionary<string, object> o && o.TryGetValue("color", out var hex) ? Hex((string)hex) : fallback;
918
+ }
919
+
493
920
  static class Physics
494
921
  {
495
922
  public static bool Add(GameObject go, string type, Dictionary<string, object> f)