@scenoco-three/unity 0.9.8 → 1.0.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.
- package/README.md +21 -5
- package/dist/cli.js +9 -2
- package/dist/convert.d.ts +35 -5
- package/dist/convert.js +74 -17
- package/dist/export.d.ts +33 -4
- package/dist/export.js +122 -7
- package/dist/input.d.ts +14 -0
- package/dist/input.js +73 -0
- package/dist/page.d.ts +25 -0
- package/dist/page.js +347 -0
- package/dist/stub.d.ts +45 -0
- package/dist/stub.js +324 -0
- package/package.json +4 -3
- package/unity/Driver/SceNoCo.Driver.asmdef +32 -0
- package/unity/Driver/SceNoCoDriver.cs +697 -0
- package/unity/KeepAcrossScenes.cs +25 -0
- package/unity/PORTING.md +153 -0
- package/unity/SceNoCoImporter.cs +322 -13
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Written by scenoco-unity on every export — edits here are overwritten.
|
|
2
|
+
using UnityEngine;
|
|
3
|
+
|
|
4
|
+
namespace SceNoCo
|
|
5
|
+
{
|
|
6
|
+
/// <summary>
|
|
7
|
+
/// Keeps its object when a scene loads: the first scene's Input object — its EventSystem and UI input
|
|
8
|
+
/// module — stays for the whole game, as the page's input does on the web.
|
|
9
|
+
/// </summary>
|
|
10
|
+
[DisallowMultipleComponent]
|
|
11
|
+
public sealed class KeepAcrossScenes : MonoBehaviour
|
|
12
|
+
{
|
|
13
|
+
void Awake()
|
|
14
|
+
{
|
|
15
|
+
// One of a kind: a scene played on its own may hold another.
|
|
16
|
+
#if UNITY_6000_6_OR_NEWER
|
|
17
|
+
foreach (var other in FindObjectsByType<KeepAcrossScenes>())
|
|
18
|
+
#else
|
|
19
|
+
foreach (var other in FindObjectsByType<KeepAcrossScenes>(FindObjectsSortMode.None))
|
|
20
|
+
#endif
|
|
21
|
+
if (other != this && other.name == name) { Destroy(gameObject); return; }
|
|
22
|
+
DontDestroyOnLoad(gameObject);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
package/unity/PORTING.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Porting a SceNoCo game to this Unity project
|
|
2
|
+
|
|
3
|
+
`scenoco-unity` wrote the game here as Unity's own assets — prefabs, scenes, meshes, materials,
|
|
4
|
+
particle systems, the page as UXML and USS, the input actions, the project's rendering settings — and
|
|
5
|
+
the game's code as C# stubs holding its TypeScript. What is left is the code, file by file. This card
|
|
6
|
+
is the rules for that. It is rewritten by every export.
|
|
7
|
+
|
|
8
|
+
## What is here
|
|
9
|
+
|
|
10
|
+
- `Assets/Prefabs`, `Assets/Scenes`, `Assets/Meshes`, `Assets/Materials`, `Assets/Textures`: built by
|
|
11
|
+
`unity command scenoco.import` (or **SceNoCo ▸ Import**), which lists what did not come across.
|
|
12
|
+
Read every warning it prints.
|
|
13
|
+
- `Assets/Scripts/<Behaviour>.cs`: one stub per behaviour. Its wired fields are real C# fields, and the
|
|
14
|
+
prefabs already set them; keep their names. Every other field, and every method, holds its
|
|
15
|
+
TypeScript as comments; so does the code its file holds outside the class. Write the C# in its
|
|
16
|
+
place and delete the comment. A stub compiles as it is, so port one at a time and keep the project
|
|
17
|
+
compiling. Stubs are written once and never overwritten.
|
|
18
|
+
- `Assets/Scripts/Modules/*.cs`: every other module of the game — helpers, tables, the entry
|
|
19
|
+
`main.ts` — as its TypeScript in comments. Decide what each becomes (below).
|
|
20
|
+
- `Assets/UI`: the page — one `.uxml` per `UIDocument`, one per `<template>`, `Page.uss`, its images
|
|
21
|
+
and its fonts. Rewritten by every export: change the page, not these.
|
|
22
|
+
- `Assets/SceNoCo/Input/SceNoCo.inputactions`: the project-wide input actions.
|
|
23
|
+
- `Assets/SceNoCo/Driver`: the `scenoco` commands that drive the game in Play mode (below).
|
|
24
|
+
|
|
25
|
+
## Code
|
|
26
|
+
|
|
27
|
+
- **Hooks are Unity's messages.** `awake` is `Awake`, `update` is `Update`, `onTriggerEnter` is
|
|
28
|
+
`OnTriggerEnter`; the stub already names them, and `update(dt)`'s `dt` is `Time.deltaTime`. Other
|
|
29
|
+
methods are PascalCase.
|
|
30
|
+
- **The world is mirrored on Z.** three.js is right-handed, Unity left-handed; the export negates z.
|
|
31
|
+
Negate z in every vector literal and every z the code computes; a rotation about x or y turns the
|
|
32
|
+
other way. `lookAt`, forward vectors and cameras need the same care. The prefabs are already
|
|
33
|
+
mirrored: only code is left.
|
|
34
|
+
- **A node's `position`, `rotation` and `scale` are local**: `transform.localPosition`,
|
|
35
|
+
`localRotation`, `localScale`. `getWorldPosition` is `transform.position`. `eulerAngles` are degrees
|
|
36
|
+
on both sides; three's `rotation` is radians.
|
|
37
|
+
- **Behaviours read as Unity's already**: `getComponent<T>` is `GetComponent<T>()`, `instantiate`,
|
|
38
|
+
`destroy`, `Time`, `Mathf`, `Random`, `sendMessage` keep their meaning. A prefab a behaviour
|
|
39
|
+
instantiates is a `GameObject` field set to its prefab asset. `findObjectOfType` is
|
|
40
|
+
`FindFirstObjectByType`, `findObjectsOfType` is `FindObjectsByType<T>()` (before Unity 6.6,
|
|
41
|
+
`FindObjectsByType<T>(FindObjectsSortMode.None)`).
|
|
42
|
+
- **Coroutines**: a `*generator` is an `IEnumerator`, `this.startCoroutine(this.x())` is
|
|
43
|
+
`StartCoroutine(X())`, `yield new WaitForSeconds(s)` is the same, `yield null` waits a frame.
|
|
44
|
+
- **Events**: an `Event<T>` field is a C# `event Action<T>`; `listen(e, f)` is `e += f`, and its
|
|
45
|
+
removal belongs in `OnDestroy`.
|
|
46
|
+
- **Colours are `Color`**, as SceNoCo's are three's `Color`: a field the scenes wire comes across
|
|
47
|
+
typed. A colour written as a string in TypeScript is a bug to fix in the game.
|
|
48
|
+
- **Materials**: three's `color`, `emissive` and `metalness` are URP Lit's `_BaseColor`,
|
|
49
|
+
`_EmissionColor` and `_Metallic`, and `node.material` is `GetComponent<Renderer>().material` — a
|
|
50
|
+
copy of its own, as a three material written in an element is. URP has no emissive intensity: the
|
|
51
|
+
importer wrote `_EmissionColor` as the colour's linear value times it. Code that animates a glow
|
|
52
|
+
keeps the colour, as the TSX wrote it, and sets `(color.linear * intensity).gamma`.
|
|
53
|
+
- **Physics layers** came across: SceNoCo's layer n is Unity's user layer n + 7, named after the
|
|
54
|
+
game's own constant (`Layer.ball`), set on the objects, and the pairs `ignoreLayerCollision` set are
|
|
55
|
+
in the project's Physics settings. Code that names a layer adds 7.
|
|
56
|
+
- **Numbers**: `number` is `float`, or `int` where it counts. Keep the units: SceNoCo's are Unity's.
|
|
57
|
+
A union field the scenes wire stays as its stub types it — `string`, `float` — so the prefabs keep
|
|
58
|
+
their values. **Never change a wired field's type**: Unity drops a value it cannot read, and the
|
|
59
|
+
next scene saved loses it for good. If one must change, run `unity command scenoco.import` before
|
|
60
|
+
saving anything.
|
|
61
|
+
- **Particle systems** came across as Unity's own, module by module: `play()`, `stop()` and
|
|
62
|
+
`isPlaying` are the same.
|
|
63
|
+
|
|
64
|
+
## Input
|
|
65
|
+
|
|
66
|
+
SceNoCo's `Input` is Unity's Input Manager by name; here it is the Input System, which a URP project
|
|
67
|
+
uses alone. The named axes and buttons are actions of the same names in the project-wide actions —
|
|
68
|
+
no class of your own between the game and them:
|
|
69
|
+
|
|
70
|
+
| TypeScript | C# |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `Input.getAxis('Horizontal')`, `getAxisRaw` | `InputSystem.actions["Horizontal"].ReadValue<float>()` |
|
|
73
|
+
| `Input.getButtonDown('Jump')`, `getButton`, `getButtonUp` | `InputSystem.actions["Jump"].WasPressedThisFrame()`, `IsPressed()`, `WasReleasedThisFrame()` |
|
|
74
|
+
| `Input.getKeyDown(KeyCode.Space)` | `Keyboard.current.spaceKey.wasPressedThisFrame` |
|
|
75
|
+
| `Input.getKeyDown(KeyCode.JoystickButton0)` | `Gamepad.current?.buttonSouth.wasPressedThisFrame` — 1 is `buttonEast`, 2 `buttonWest`, 3 `buttonNorth`, 9 `startButton` |
|
|
76
|
+
| `Input.getMouseButtonDown(MouseButton.Left)` | `Pointer.current.press.wasPressedThisFrame` — a finger too |
|
|
77
|
+
| `Input.mousePosition`, `Input.pointer` | `Pointer.current.position.ReadValue()` (pixels, from the bottom-left) |
|
|
78
|
+
| `Input.mouseDelta` | `Pointer.current.delta.ReadValue()` |
|
|
79
|
+
| `Input.getButtonDown('Continue')` from a `data-button` | the element's click: `root.Q("banner").RegisterCallback<ClickEvent>(…)` |
|
|
80
|
+
|
|
81
|
+
`getAxis` eases toward the keys in SceNoCo and Unity's legacy Input; an action does not. Where the
|
|
82
|
+
easing matters, ease the value in the behaviour (`Mathf.MoveTowards` at the axis' sensitivity, 3/s).
|
|
83
|
+
The first scene has an `Input` object — the UI's EventSystem with its Input System module — kept for
|
|
84
|
+
the whole game: UI clicks need it.
|
|
85
|
+
|
|
86
|
+
## Code outside behaviours
|
|
87
|
+
|
|
88
|
+
`Assets/Scripts/Modules` holds the rest, as TypeScript, for you to decide:
|
|
89
|
+
|
|
90
|
+
- helpers — functions — are a `static class`;
|
|
91
|
+
- a union of names (`'title' | 'ready'`) is an `enum`;
|
|
92
|
+
- a table of specs a designer tunes — a `Record` of towers, enemies, levels — is a **ScriptableObject**:
|
|
93
|
+
one class per record type (`TowerSpec : ScriptableObject`, a nested object a `[Serializable]`
|
|
94
|
+
class), one `.asset` per entry made by an Editor script run with `unity command script.run`, and a
|
|
95
|
+
serialized field on the behaviour that read the table, holding the assets;
|
|
96
|
+
- a constant only one behaviour uses is a serialized field on it;
|
|
97
|
+
- `main.ts` set up the renderer: its tone mapping and post-processing are a Volume (below).
|
|
98
|
+
|
|
99
|
+
## UI
|
|
100
|
+
|
|
101
|
+
The page came across as it is, rule by rule. What code does with it:
|
|
102
|
+
|
|
103
|
+
- `getElementById` (or the page's `$`) is `root.Q("id")` on `GetComponent<UIDocument>().rootVisualElement`,
|
|
104
|
+
found once in `Awake` or `OnEnable`; `textContent` is `Label.text` (an element code fills is a
|
|
105
|
+
`Label`); `classList.add`, `remove`, `toggle` are `AddToClassList`, `RemoveFromClassList`,
|
|
106
|
+
`EnableInClassList`; `transitionend` is `TransitionEndEvent`; `style.left = '30%'` is
|
|
107
|
+
`style.left = Length.Percent(30)`.
|
|
108
|
+
- A `<template>` is `Assets/UI/<id>.uxml`: give the behaviour a `VisualTreeAsset` field set to it, and
|
|
109
|
+
`Instantiate()` where the code cloned it.
|
|
110
|
+
- The export says in its warnings what USS has no way to write. Change the page so it ports, and
|
|
111
|
+
export again: the UI is never hand-edited here.
|
|
112
|
+
|
|
113
|
+
## Look
|
|
114
|
+
|
|
115
|
+
The project's settings are the export's, for a three.js game: Linear colour space, HDR, no MSAA (as
|
|
116
|
+
SceNoCo renders), Forward+ (no light limit per object, as three has none), soft shadows, and no
|
|
117
|
+
skybox reflections in a scene with no environment. Lights divide by π; fog and ambient light come from
|
|
118
|
+
the scene. Cameras draw with no post-processing, as three's default renderer does. What `main.ts` set
|
|
119
|
+
up in code is the port's:
|
|
120
|
+
|
|
121
|
+
- **Tone mapping, exposure and bloom** (`renderer.toneMapping`, an `EffectComposer`) are a URP Volume:
|
|
122
|
+
a profile with Tonemapping (ACES), Color Adjustments (post exposure is log₂ of three's
|
|
123
|
+
`toneMappingExposure`) and Bloom, on a GameObject kept across scenes, and Post Processing switched
|
|
124
|
+
on for each camera. Bloom's settings do not carry over by number: tune it against the web game. A
|
|
125
|
+
profile made from code needs `EditorUtility.SetDirty` before it is saved, or its list of components
|
|
126
|
+
is lost.
|
|
127
|
+
|
|
128
|
+
## Checking the port
|
|
129
|
+
|
|
130
|
+
Drive both games through the same scenario and compare. The web game is driven with
|
|
131
|
+
`window.__scenoco` (its `help()` says how); this one with the `scenoco` commands, which take the same
|
|
132
|
+
verbs. They need Unity's CLI and its Pipeline package (`unity pipeline install`).
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
unity command scenoco.help
|
|
136
|
+
unity command scenoco.import
|
|
137
|
+
unity command scenoco.setup --width 1080 --height 1920 # the web game's window size
|
|
138
|
+
unity command scenoco.play
|
|
139
|
+
unity command scenoco.ready # Play mode restarts the command server: repeat until it answers
|
|
140
|
+
unity command scenoco.pause
|
|
141
|
+
unity command scenoco.press --key Space
|
|
142
|
+
unity command scenoco.until --target Game.phase --equals playing
|
|
143
|
+
unity command scenoco.read --target Player
|
|
144
|
+
unity command capture.game_view -- --save_path Screenshots/after-start.png
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Step the same number of frames on both sides and the two should read the same values: 1/60 s a
|
|
148
|
+
frame on both clocks, the same fixed step (0.02 s) for physics. Compare values — `read --target
|
|
149
|
+
Ball.transform.position` here, `__scenoco.eval(...)` there — rather than screenshots: they agree
|
|
150
|
+
within a physics step. When a reading differs, the C# is wrong, not the scene: the scene came across
|
|
151
|
+
by the exporter. UI timed with `WaitForSecondsRealtime`, and UI Toolkit's transitions, run on real
|
|
152
|
+
time on both sides, so they do not line up frame for frame. A wait longer than the CLI's 30 s takes
|
|
153
|
+
`--timeout 120` after the verb.
|
package/unity/SceNoCoImporter.cs
CHANGED
|
@@ -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
|
-
|
|
66
|
-
|
|
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
|
|
69
|
-
if (
|
|
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
|
-
|
|
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,
|
|
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
|
|
234
|
-
|
|
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;
|
|
@@ -290,6 +323,10 @@ namespace SceNoCo
|
|
|
290
323
|
RenderSettings.ambientMode = AmbientMode.Flat;
|
|
291
324
|
RenderSettings.ambientLight = Color.black;
|
|
292
325
|
}
|
|
326
|
+
// three lights a surface with no environment by nothing but its lights: no skybox reflections either.
|
|
327
|
+
RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom;
|
|
328
|
+
RenderSettings.customReflectionTexture = null;
|
|
329
|
+
RenderSettings.reflectionIntensity = s.ContainsKey("environment") ? 1 : 0;
|
|
293
330
|
EditorSceneManager.SaveScene(scene, path);
|
|
294
331
|
}
|
|
295
332
|
finally
|
|
@@ -298,6 +335,7 @@ namespace SceNoCo
|
|
|
298
335
|
{
|
|
299
336
|
SceneManager.SetActiveScene(previous);
|
|
300
337
|
EditorSceneManager.CloseScene(scene, true);
|
|
338
|
+
if (beside) EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
|
|
301
339
|
}
|
|
302
340
|
}
|
|
303
341
|
}
|
|
@@ -319,6 +357,7 @@ namespace SceNoCo
|
|
|
319
357
|
var r = Floats(n["rotation"]);
|
|
320
358
|
go.transform.localRotation = new Quaternion(r[0], r[1], r[2], r[3]);
|
|
321
359
|
go.transform.localScale = V3(n["scale"]);
|
|
360
|
+
if (n.TryGetValue("layer", out var layer)) go.layer = Convert.ToInt32(layer, CultureInfo.InvariantCulture);
|
|
322
361
|
|
|
323
362
|
if (n.TryGetValue("mesh", out var mesh))
|
|
324
363
|
{
|
|
@@ -341,6 +380,8 @@ namespace SceNoCo
|
|
|
341
380
|
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
381
|
else go.AddComponent(t);
|
|
343
382
|
}
|
|
383
|
+
else if (type == "ParticleSystem") Particles.Add(go, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"));
|
|
384
|
+
else if (type == "UIDocument") MakeDocument(go, Obj(comp["fields"]), Where(comp, n));
|
|
344
385
|
else if (!Physics.Add(go, type, Obj(comp["fields"]))) warnings.Add($"{Where(comp, n)}: {type} has no Unity counterpart here — left off.");
|
|
345
386
|
}
|
|
346
387
|
|
|
@@ -437,6 +478,51 @@ namespace SceNoCo
|
|
|
437
478
|
return t != null ? go.GetComponent(t) : go.GetComponent(wanted);
|
|
438
479
|
}
|
|
439
480
|
|
|
481
|
+
// --- the page and input ------------------------------------------------------------------
|
|
482
|
+
|
|
483
|
+
/// <summary>A UIDocument for the page's element: its UXML, and Panel Settings that scale as core's UIDocument does.</summary>
|
|
484
|
+
static void MakeDocument(GameObject go, Dictionary<string, object> f, string where)
|
|
485
|
+
{
|
|
486
|
+
var element = f.TryGetValue("element", out var e) ? (string)e : "ui";
|
|
487
|
+
var documents = ui != null && ui.TryGetValue("documents", out var d) ? Obj(d) : new Dictionary<string, object>();
|
|
488
|
+
if (!documents.TryGetValue(element, out var uxml))
|
|
489
|
+
{
|
|
490
|
+
warnings.Add($"{where}: no UXML for the element \"{element}\" — the page has no element with that id.");
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
var path = $"Assets/UI/{element}.panel.asset";
|
|
494
|
+
var panel = AssetDatabase.LoadAssetAtPath<PanelSettings>(path);
|
|
495
|
+
if (panel == null)
|
|
496
|
+
{
|
|
497
|
+
panel = ScriptableObject.CreateInstance<PanelSettings>();
|
|
498
|
+
SaveAsset(panel, path);
|
|
499
|
+
}
|
|
500
|
+
panel.themeStyleSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(Str(ui, "theme"));
|
|
501
|
+
panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
|
|
502
|
+
panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
|
|
503
|
+
var size = f.TryGetValue("referenceResolution", out var r) ? Floats(Obj(r)["v2"]) : new[] { 1280f, 720f };
|
|
504
|
+
panel.referenceResolution = new Vector2Int(Mathf.RoundToInt(size[0]), Mathf.RoundToInt(size[1]));
|
|
505
|
+
panel.match = Num(f, "match", 0.5f);
|
|
506
|
+
// In the page's order: an element written later draws over an earlier one.
|
|
507
|
+
panel.sortingOrder = documents.Keys.ToList().IndexOf(element);
|
|
508
|
+
EditorUtility.SetDirty(panel);
|
|
509
|
+
var doc = go.AddComponent<UIDocument>();
|
|
510
|
+
doc.panelSettings = panel;
|
|
511
|
+
doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>((string)uxml);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/// <summary>The first scene's Input object: the UI's EventSystem and its Input System module, kept for the whole game.</summary>
|
|
515
|
+
static void MakeInput()
|
|
516
|
+
{
|
|
517
|
+
var go = new GameObject("Input");
|
|
518
|
+
foreach (var name in new[] { "UnityEngine.EventSystems.EventSystem, UnityEngine.UI", "UnityEngine.InputSystem.UI.InputSystemUIInputModule, Unity.InputSystem", "SceNoCo.KeepAcrossScenes, Assembly-CSharp" })
|
|
519
|
+
{
|
|
520
|
+
var t = Type.GetType(name);
|
|
521
|
+
if (t != null) go.AddComponent(t);
|
|
522
|
+
else warnings.Add($"Input: {name.Split(',')[0]} is not in this project — add the Input System and UI packages.");
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
440
526
|
static GameObject Find(GameObject root, string path)
|
|
441
527
|
{
|
|
442
528
|
var t = root.transform;
|
|
@@ -477,10 +563,8 @@ namespace SceNoCo
|
|
|
477
563
|
static Type GameType(string name)
|
|
478
564
|
{
|
|
479
565
|
if (types.TryGetValue(name, out var known)) return known;
|
|
480
|
-
var found =
|
|
481
|
-
.
|
|
482
|
-
.SelectMany(a => { try { return a.GetTypes(); } catch { return new Type[0]; } })
|
|
483
|
-
.FirstOrDefault(t => t.Name == name && typeof(MonoBehaviour).IsAssignableFrom(t));
|
|
566
|
+
var found = TypeCache.GetTypesDerivedFrom<MonoBehaviour>()
|
|
567
|
+
.FirstOrDefault(t => t.Name == name && !t.Assembly.FullName.StartsWith("Unity"));
|
|
484
568
|
types[name] = found;
|
|
485
569
|
return found;
|
|
486
570
|
}
|
|
@@ -490,6 +574,231 @@ namespace SceNoCo
|
|
|
490
574
|
|
|
491
575
|
// --- physics: SceNoCo's rapier and box2d components are Unity's own --------------------
|
|
492
576
|
|
|
577
|
+
/// <summary>The project's own settings: what a three.js game draws and reads like, in Unity 6.</summary>
|
|
578
|
+
static class Project
|
|
579
|
+
{
|
|
580
|
+
/// <summary>
|
|
581
|
+
/// three.js renders in linear space to an sRGB canvas, with no tone mapping, no antialiasing (SceNoCo's
|
|
582
|
+
/// default), no light limit per object and no environment: Linear colour space, HDR kept for a bloom a
|
|
583
|
+
/// game adds, MSAA off, render scale 1, Forward+, soft shadows. Applied to every URP asset in the
|
|
584
|
+
/// project, through their serialized fields, so a project without URP still compiles this.
|
|
585
|
+
/// </summary>
|
|
586
|
+
public static void Recommended()
|
|
587
|
+
{
|
|
588
|
+
PlayerSettings.colorSpace = ColorSpace.Linear;
|
|
589
|
+
foreach (var guid in AssetDatabase.FindAssets("t:UniversalRenderPipelineAsset"))
|
|
590
|
+
{
|
|
591
|
+
var asset = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid));
|
|
592
|
+
var so = new SerializedObject(asset);
|
|
593
|
+
Set(so, "m_SupportsHDR", p => p.boolValue = true);
|
|
594
|
+
Set(so, "m_MSAA", p => p.intValue = 1);
|
|
595
|
+
Set(so, "m_RenderScale", p => p.floatValue = 1);
|
|
596
|
+
Set(so, "m_SoftShadowsSupported", p => p.boolValue = true);
|
|
597
|
+
so.ApplyModifiedPropertiesWithoutUndo();
|
|
598
|
+
}
|
|
599
|
+
foreach (var guid in AssetDatabase.FindAssets("t:UniversalRendererData"))
|
|
600
|
+
{
|
|
601
|
+
var so = new SerializedObject(AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)));
|
|
602
|
+
// Forward+: no cap of eight lights per object — three has none.
|
|
603
|
+
Set(so, "m_RenderingMode", p => p.intValue = 2);
|
|
604
|
+
so.ApplyModifiedPropertiesWithoutUndo();
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
static void Set(SerializedObject so, string name, Action<SerializedProperty> set)
|
|
609
|
+
{
|
|
610
|
+
var p = so.FindProperty(name);
|
|
611
|
+
if (p != null) set(p);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/// <summary>The game's layers by name, and the pairs its physics lets pass through each other.</summary>
|
|
615
|
+
public static void Layers(Dictionary<string, object> l)
|
|
616
|
+
{
|
|
617
|
+
var tags = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
|
|
618
|
+
var names = tags.FindProperty("layers");
|
|
619
|
+
foreach (var pair in Obj(l["names"]))
|
|
620
|
+
{
|
|
621
|
+
var index = int.Parse(pair.Key, CultureInfo.InvariantCulture);
|
|
622
|
+
var current = names.GetArrayElementAtIndex(index).stringValue;
|
|
623
|
+
if (string.IsNullOrEmpty(current) || current.StartsWith("Layer ")) names.GetArrayElementAtIndex(index).stringValue = (string)pair.Value;
|
|
624
|
+
else if (current != (string)pair.Value) warnings.Add($"layers: Unity layer {index} is \"{current}\" already — the game's {pair.Value} shares it.");
|
|
625
|
+
}
|
|
626
|
+
tags.ApplyModifiedPropertiesWithoutUndo();
|
|
627
|
+
Matrix("ProjectSettings/Physics2DSettings.asset", List(l["ignore2D"]).Select(Floats));
|
|
628
|
+
Matrix("ProjectSettings/DynamicsManager.asset", List(l["ignore3D"]).Select(Floats));
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/// <summary>
|
|
632
|
+
/// The pairs written into the project's collision matrix itself: IgnoreLayerCollision called in the
|
|
633
|
+
/// Editor lasts only until the settings reload. A row's bit set is "collides".
|
|
634
|
+
/// </summary>
|
|
635
|
+
static void Matrix(string settings, IEnumerable<float[]> pairs)
|
|
636
|
+
{
|
|
637
|
+
var so = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(settings)[0]);
|
|
638
|
+
var rows = so.FindProperty("m_LayerCollisionMatrix");
|
|
639
|
+
if (rows == null) return;
|
|
640
|
+
foreach (var pair in pairs)
|
|
641
|
+
{
|
|
642
|
+
int a = (int)pair[0], b = (int)pair[1];
|
|
643
|
+
rows.GetArrayElementAtIndex(a).longValue &= ~(1L << b);
|
|
644
|
+
rows.GetArrayElementAtIndex(b).longValue &= ~(1L << a);
|
|
645
|
+
}
|
|
646
|
+
so.ApplyModifiedPropertiesWithoutUndo();
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/// <summary>SceNoCo's named axes and buttons as the project-wide actions: `InputSystem.actions["Horizontal"]`.</summary>
|
|
650
|
+
public static void Input(string path)
|
|
651
|
+
{
|
|
652
|
+
AssetDatabase.ImportAsset(path);
|
|
653
|
+
var asset = AssetDatabase.LoadMainAssetAtPath(path);
|
|
654
|
+
var system = Type.GetType("UnityEngine.InputSystem.InputSystem, Unity.InputSystem");
|
|
655
|
+
var actions = system?.GetProperty("actions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
|
|
656
|
+
if (asset == null || actions == null || !actions.CanWrite)
|
|
657
|
+
{
|
|
658
|
+
warnings.Add($"input: {path} is not the project-wide actions — set it in Project Settings ▸ Input System Package.");
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
actions.SetValue(null, asset);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/// <summary>
|
|
666
|
+
/// A SceNoCo ParticleSystem's effect — Shuriken's modules under Shuriken's names — as Unity's own
|
|
667
|
+
/// ParticleSystem. three.quarks emits along +Z like Unity; the mirror on Z turns a cone or a hemisphere round.
|
|
668
|
+
/// </summary>
|
|
669
|
+
static class Particles
|
|
670
|
+
{
|
|
671
|
+
public static void Add(GameObject go, Dictionary<string, object> f, Action<string> warn)
|
|
672
|
+
{
|
|
673
|
+
if (!f.TryGetValue("effect", out var e) || !(e is Dictionary<string, object> eo) || !eo.ContainsKey("object"))
|
|
674
|
+
{
|
|
675
|
+
warn("ParticleSystem has no effect it could read — left off.");
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
var c = Fields(eo);
|
|
679
|
+
var ps = go.AddComponent<ParticleSystem>();
|
|
680
|
+
ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
|
681
|
+
var main = ps.main;
|
|
682
|
+
main.duration = Num(c, "duration", 5);
|
|
683
|
+
main.loop = Bool(c, "looping", true);
|
|
684
|
+
main.prewarm = Bool(c, "prewarm", false);
|
|
685
|
+
main.startLifetime = Num(c, "startLifetime", 5);
|
|
686
|
+
main.startSpeed = Num(c, "startSpeed", 5);
|
|
687
|
+
main.startSize = Num(c, "startSize", 1);
|
|
688
|
+
main.startRotation = Num(c, "startRotation", 0) * Mathf.Deg2Rad;
|
|
689
|
+
main.startColor = ColorOf(c, "startColor", Color.white);
|
|
690
|
+
main.gravityModifier = Num(c, "gravityModifier", 0);
|
|
691
|
+
main.simulationSpace = Str(c, "simulationSpace") == "World" ? ParticleSystemSimulationSpace.World : ParticleSystemSimulationSpace.Local;
|
|
692
|
+
main.playOnAwake = !f.TryGetValue("playOnAwake", out var awake) || (bool)awake;
|
|
693
|
+
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
|
|
694
|
+
|
|
695
|
+
var emission = ps.emission;
|
|
696
|
+
var em = Sub(c, "emission");
|
|
697
|
+
emission.rateOverTime = Num(em, "rateOverTime", 10);
|
|
698
|
+
if (em.TryGetValue("bursts", out var bursts))
|
|
699
|
+
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());
|
|
700
|
+
|
|
701
|
+
var shape = ps.shape;
|
|
702
|
+
var sh = Sub(c, "shape");
|
|
703
|
+
var type = sh.ContainsKey("type") ? Str(sh, "type") : "Cone";
|
|
704
|
+
shape.radius = Num(sh, "radius", 1);
|
|
705
|
+
shape.angle = Num(sh, "angle", 25);
|
|
706
|
+
shape.arc = Num(sh, "arc", 360);
|
|
707
|
+
switch (type)
|
|
708
|
+
{
|
|
709
|
+
case "Sphere": shape.shapeType = ParticleSystemShapeType.Sphere; break;
|
|
710
|
+
case "Hemisphere": shape.shapeType = ParticleSystemShapeType.Hemisphere; shape.rotation = new Vector3(0, 180, 0); break;
|
|
711
|
+
case "Circle": shape.shapeType = ParticleSystemShapeType.Circle; break;
|
|
712
|
+
case "Donut": shape.shapeType = ParticleSystemShapeType.Donut; break;
|
|
713
|
+
case "Rectangle": shape.shapeType = ParticleSystemShapeType.Rectangle; shape.scale = new Vector3(shape.radius * 2, shape.radius * 2, 1); break;
|
|
714
|
+
case "Point": shape.shapeType = ParticleSystemShapeType.Sphere; shape.radius = 0.0001f; break;
|
|
715
|
+
default: shape.shapeType = ParticleSystemShapeType.Cone; shape.rotation = new Vector3(0, 180, 0); break;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
if (c.TryGetValue("noise", out _))
|
|
719
|
+
{
|
|
720
|
+
var n = Sub(c, "noise");
|
|
721
|
+
var noise = ps.noise;
|
|
722
|
+
noise.enabled = true;
|
|
723
|
+
noise.strength = Num(n, "strength", 1);
|
|
724
|
+
noise.frequency = Num(n, "frequency", 2);
|
|
725
|
+
}
|
|
726
|
+
if (c.TryGetValue("colorOverLifetime", out _))
|
|
727
|
+
{
|
|
728
|
+
var colors = List(Obj(Sub(c, "colorOverLifetime")["colors"])["array"]).Select(x => Hex(Str(Obj(x), "color"))).ToArray();
|
|
729
|
+
if (colors.Length > 0)
|
|
730
|
+
{
|
|
731
|
+
// Evenly spaced, as the effect writes them; full alpha, fading out over the last third, as three.quarks does.
|
|
732
|
+
var keys = colors.Select((col, i) => new GradientColorKey(col, colors.Length == 1 ? 0 : i / (float)(colors.Length - 1))).Take(8).ToArray();
|
|
733
|
+
var gradient = new Gradient();
|
|
734
|
+
gradient.SetKeys(keys, new[] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 0.7f), new GradientAlphaKey(0, 1) });
|
|
735
|
+
var col = ps.colorOverLifetime;
|
|
736
|
+
col.enabled = true;
|
|
737
|
+
col.color = gradient;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (c.TryGetValue("sizeOverLifetime", out _))
|
|
741
|
+
{
|
|
742
|
+
var values = Floats(Obj(Sub(c, "sizeOverLifetime")["curve"])["array"]);
|
|
743
|
+
if (values.Length > 0)
|
|
744
|
+
{
|
|
745
|
+
var curve = new AnimationCurve(values.Select((v, i) => new Keyframe(values.Length == 1 ? 0 : i / (float)(values.Length - 1), v)).ToArray());
|
|
746
|
+
for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
|
|
747
|
+
for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
|
|
748
|
+
var size = ps.sizeOverLifetime;
|
|
749
|
+
size.enabled = true;
|
|
750
|
+
size.size = new ParticleSystem.MinMaxCurve(1, curve);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (c.TryGetValue("rotationOverLifetime", out _))
|
|
754
|
+
{
|
|
755
|
+
var rot = ps.rotationOverLifetime;
|
|
756
|
+
rot.enabled = true;
|
|
757
|
+
rot.z = Num(Sub(c, "rotationOverLifetime"), "angularVelocity", 0) * Mathf.Deg2Rad;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
var r = Sub(c, "renderer");
|
|
761
|
+
var renderer = go.GetComponent<ParticleSystemRenderer>();
|
|
762
|
+
renderer.renderMode = Str(r, "renderMode") switch
|
|
763
|
+
{
|
|
764
|
+
"StretchedBillboard" => ParticleSystemRenderMode.Stretch,
|
|
765
|
+
"HorizontalBillboard" => ParticleSystemRenderMode.HorizontalBillboard,
|
|
766
|
+
"VerticalBillboard" => ParticleSystemRenderMode.VerticalBillboard,
|
|
767
|
+
"Mesh" => ParticleSystemRenderMode.Mesh,
|
|
768
|
+
_ => ParticleSystemRenderMode.Billboard,
|
|
769
|
+
};
|
|
770
|
+
renderer.sharedMaterial = SharedMaterial(Str(r, "blending") == "Alpha" ? "Alpha" : "Additive");
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/// <summary>One material per blending, shared by every system: URP's particle shader, Unity's soft round sprite.</summary>
|
|
774
|
+
static Material SharedMaterial(string blending)
|
|
775
|
+
{
|
|
776
|
+
var path = $"Assets/Materials/Particles-{blending}.mat";
|
|
777
|
+
var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
|
|
778
|
+
if (mat != null) return mat;
|
|
779
|
+
var shader = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit");
|
|
780
|
+
mat = new Material(shader);
|
|
781
|
+
mat.SetTexture("_BaseMap", AssetDatabase.GetBuiltinExtraResource<Texture2D>("Default-Particle.psd"));
|
|
782
|
+
mat.SetFloat("_Surface", 1);
|
|
783
|
+
mat.SetFloat("_Blend", blending == "Additive" ? 2 : 0);
|
|
784
|
+
mat.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha);
|
|
785
|
+
mat.SetFloat("_DstBlend", (float)(blending == "Additive" ? BlendMode.One : BlendMode.OneMinusSrcAlpha));
|
|
786
|
+
mat.SetFloat("_ZWrite", 0);
|
|
787
|
+
mat.SetOverrideTag("RenderType", "Transparent");
|
|
788
|
+
mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
|
789
|
+
mat.renderQueue = (int)RenderQueue.Transparent;
|
|
790
|
+
SaveAsset(mat, path);
|
|
791
|
+
return mat;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
static Dictionary<string, object> Fields(Dictionary<string, object> o) => Obj(Obj(o["object"])["fields"]);
|
|
795
|
+
static Dictionary<string, object> Sub(Dictionary<string, object> c, string key) =>
|
|
796
|
+
c.TryGetValue(key, out var v) && v is Dictionary<string, object> d && d.ContainsKey("object") ? Fields(d) : new Dictionary<string, object>();
|
|
797
|
+
static bool Bool(Dictionary<string, object> d, string key, bool fallback) => d.TryGetValue(key, out var v) && v is bool b ? b : fallback;
|
|
798
|
+
static Color ColorOf(Dictionary<string, object> d, string key, Color fallback) =>
|
|
799
|
+
d.TryGetValue(key, out var v) && v is Dictionary<string, object> o && o.TryGetValue("color", out var hex) ? Hex((string)hex) : fallback;
|
|
800
|
+
}
|
|
801
|
+
|
|
493
802
|
static class Physics
|
|
494
803
|
{
|
|
495
804
|
public static bool Add(GameObject go, string type, Dictionary<string, object> f)
|