@scenoco-three/unity 1.3.1 → 1.5.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/dist/cli.js +8 -5
- package/dist/convert.d.ts +39 -0
- package/dist/convert.js +324 -38
- package/dist/export.d.ts +22 -3
- package/dist/export.js +243 -33
- package/dist/page.d.ts +2 -0
- package/dist/page.js +30 -12
- package/dist/stub.d.ts +7 -2
- package/dist/stub.js +66 -25
- package/dist/twin.d.ts +52 -0
- package/dist/twin.js +1074 -0
- package/package.json +2 -2
- package/unity/KeepAcrossScenes.cs +9 -2
- package/unity/PORTING.md +100 -52
- package/unity/SceNoCoImporter.cs +334 -883
- package/unity/SceNoCoValidate.cs +96 -0
- package/unity/SplineKnotNodes.cs +66 -0
- package/unity/SplineMesh.cs +255 -0
- package/unity/Driver/SceNoCo.Driver.asmdef +0 -32
- package/unity/Driver/SceNoCoDriver.cs +0 -697
package/dist/twin.js
ADDED
|
@@ -0,0 +1,1074 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The game's prefabs and scenes as Scenoco's text (`com.roro.scenoco`): a `.uprefab` beside each
|
|
3
|
+
* `.prefab` and a `.uscene` beside each `.unity`, which Unity builds into them — XAML-style, in Unity's
|
|
4
|
+
* own C# vocabulary. An attribute is what a script would assign: a Unity property set through its
|
|
5
|
+
* setter, a script's serialized field by its name. A reference is `#Name` (or `#id`), an asset its path.
|
|
6
|
+
*
|
|
7
|
+
* What the text names but cannot hold — a mesh, a material, a physics material, a URP Volume's profile,
|
|
8
|
+
* UI Toolkit's panel settings, a terrain's data — is an asset the importer makes first (`TwinAssets`).
|
|
9
|
+
* One wrong name makes Scenoco refuse a whole file, so a field is written only where its class declares
|
|
10
|
+
* it; anything else is a warning, as before.
|
|
11
|
+
*/
|
|
12
|
+
import { Matrix4, Quaternion, Vector3 } from 'three';
|
|
13
|
+
/** A twin's path: the asset's, with `.prefab` → `.uprefab` and `.unity` → `.uscene`. */
|
|
14
|
+
export const twinPath = (asset) => asset.replace(/\.prefab$/, '.uprefab').replace(/\.unity$/, '.uscene');
|
|
15
|
+
export function twins(data, options = {}) {
|
|
16
|
+
const assets = { physicsMaterials: [], particleMaterials: [], volumes: [], panels: [] };
|
|
17
|
+
const warnings = [];
|
|
18
|
+
const files = new Map();
|
|
19
|
+
const terrains = new Map(data.terrains.map((t) => [t.path, t]));
|
|
20
|
+
const volumes = hasVolume(data);
|
|
21
|
+
const prefabs = new Map(data.prefabs.map((p) => [p.path, p.root]));
|
|
22
|
+
const writer = (holder, roots) => new Writer(roots, holder, assets, warnings, options, terrains, volumes, prefabs);
|
|
23
|
+
for (const p of data.prefabs) {
|
|
24
|
+
// A prefab's root is named after its asset, as Unity names it when it saves one.
|
|
25
|
+
const node = { ...p.root, name: p.path.replace(/^.*\/|\.prefab$/g, '') };
|
|
26
|
+
const w = writer(p.path, [node]);
|
|
27
|
+
const root = w.object(node, 'Prefab', '');
|
|
28
|
+
w.finish();
|
|
29
|
+
files.set(twinPath(p.path), print(root));
|
|
30
|
+
}
|
|
31
|
+
data.scenes.forEach((s, i) => {
|
|
32
|
+
const w = writer(s.path, s.roots);
|
|
33
|
+
const scene = new El('Scene').set('name', s.path.replace(/^.*\/|\.unity$/g, ''));
|
|
34
|
+
let mainCamera = false;
|
|
35
|
+
s.roots.forEach((r, n) => {
|
|
36
|
+
const e = w.object(r, r.prefab ? 'PrefabInstance' : 'GameObject', String(n), { background: s.background });
|
|
37
|
+
// The first camera is the main one: Camera.main finds it by this tag. It hears the game too, as a
|
|
38
|
+
// new scene's Main Camera does — the page needs no listener, Unity plays nothing without one.
|
|
39
|
+
if (!mainCamera)
|
|
40
|
+
mainCamera = w.tagMainCamera(e);
|
|
41
|
+
scene.add(e);
|
|
42
|
+
});
|
|
43
|
+
if (!mainCamera)
|
|
44
|
+
warnings.push(`${s.path}: no camera in the scene.`);
|
|
45
|
+
// UI input in every scene with a page, so a level played on its own takes taps; KeepAcrossScenes keeps
|
|
46
|
+
// the first one loaded and drops the next scene's.
|
|
47
|
+
const page = (n) => n.components.some((c) => c.type === 'UIDocument') || n.children.some(page);
|
|
48
|
+
if (options.eventSystem && (i === 0 || s.roots.some(page))) {
|
|
49
|
+
scene.add(new El('GameObject').set('name', 'Input').add(new El('EventSystem'), new El('InputSystemUIInputModule'), new El('KeepAcrossScenes')));
|
|
50
|
+
}
|
|
51
|
+
w.finish();
|
|
52
|
+
files.set(twinPath(s.path), print(scene));
|
|
53
|
+
});
|
|
54
|
+
return { files, assets, warnings };
|
|
55
|
+
}
|
|
56
|
+
function hasVolume(data) {
|
|
57
|
+
const visit = (n) => n.components.some((c) => c.type === 'Volume') || n.children.some(visit);
|
|
58
|
+
return data.prefabs.some((p) => visit(p.root)) || data.scenes.some((s) => s.roots.some(visit));
|
|
59
|
+
}
|
|
60
|
+
// --- one file ----------------------------------------------------------------------------------
|
|
61
|
+
class Writer {
|
|
62
|
+
/** `#Name` where a name is the file's only one, else `#id` given to the element. */
|
|
63
|
+
refs = new Map();
|
|
64
|
+
elements = new Map();
|
|
65
|
+
/** Colliders a MeshCollider above gives a node's mesh objects: a path inside a placed model, or [] for its own mesh. */
|
|
66
|
+
meshColliders = new Map();
|
|
67
|
+
names = new Map();
|
|
68
|
+
ids = new Set();
|
|
69
|
+
idsByNode = new Map();
|
|
70
|
+
roots;
|
|
71
|
+
holder;
|
|
72
|
+
assets;
|
|
73
|
+
warnings;
|
|
74
|
+
options;
|
|
75
|
+
terrains;
|
|
76
|
+
volumes;
|
|
77
|
+
/** Each prefab's root by its asset path: what a placement is compared with. */
|
|
78
|
+
prefabs;
|
|
79
|
+
/** While comparing a copy with its prefab: the copy's path, which references are made relative to. */
|
|
80
|
+
comparing = null;
|
|
81
|
+
/** Each node's parent in this file, for where one stands in another's space (a spline's knot nodes). */
|
|
82
|
+
parents = new Map();
|
|
83
|
+
constructor(roots, holder, assets, warnings, options, terrains, volumes, prefabs) {
|
|
84
|
+
this.prefabs = prefabs;
|
|
85
|
+
this.roots = roots;
|
|
86
|
+
this.holder = holder;
|
|
87
|
+
this.assets = assets;
|
|
88
|
+
this.warnings = warnings;
|
|
89
|
+
this.options = options;
|
|
90
|
+
this.terrains = terrains;
|
|
91
|
+
this.volumes = volumes;
|
|
92
|
+
const count = (n) => {
|
|
93
|
+
this.names.set(n.name, (this.names.get(n.name) ?? 0) + 1);
|
|
94
|
+
// What a placed prefab holds is the prefab's: it is no element of this file.
|
|
95
|
+
if (!n.prefab)
|
|
96
|
+
n.children.forEach((child) => (this.parents.set(child, n), count(child)));
|
|
97
|
+
};
|
|
98
|
+
roots.forEach(count);
|
|
99
|
+
}
|
|
100
|
+
/** A node, its components and its children; `path` is its place as references give it (child indices). */
|
|
101
|
+
object(n, tag, path, scene = {}, hidden = false) {
|
|
102
|
+
const e = new El(tag);
|
|
103
|
+
this.elements.set(n, e);
|
|
104
|
+
// A placed prefab (or a prefab whose root is one, a variant) writes only how it differs from that prefab.
|
|
105
|
+
const base = n.prefab ? this.prefabs.get(n.prefab) : undefined;
|
|
106
|
+
if (tag === 'PrefabInstance')
|
|
107
|
+
e.set('prefab', n.prefab);
|
|
108
|
+
// A model file is a prefab too: one whose root is a placed model is its variant.
|
|
109
|
+
else if (n.prefab)
|
|
110
|
+
e.set('base', n.prefab);
|
|
111
|
+
e.set('name', n.name);
|
|
112
|
+
if (base) {
|
|
113
|
+
const transform = this.transform(n, base);
|
|
114
|
+
if (transform.attrs.length)
|
|
115
|
+
e.add(transform);
|
|
116
|
+
if (n.given)
|
|
117
|
+
this.overrides(n, base, e, path, path, scene, hidden);
|
|
118
|
+
return e;
|
|
119
|
+
}
|
|
120
|
+
if (n.layer)
|
|
121
|
+
e.set('layer', String(n.layer));
|
|
122
|
+
if (!n.active)
|
|
123
|
+
e.set('m_IsActive', 'false');
|
|
124
|
+
// Hidden in three while a behaviour on it runs: its renderers off, the object active.
|
|
125
|
+
const off = hidden || !n.renderersEnabled;
|
|
126
|
+
const transform = this.transform(n);
|
|
127
|
+
if (transform.attrs.length)
|
|
128
|
+
e.add(transform);
|
|
129
|
+
e.add(...this.own(n, off, scene));
|
|
130
|
+
n.children.forEach((child, i) => e.add(this.object(child, child.prefab ? 'PrefabInstance' : 'GameObject', path === '' ? String(i) : `${path}/${i}`, scene, off)));
|
|
131
|
+
this.writeMeshColliders(n, e);
|
|
132
|
+
return e;
|
|
133
|
+
}
|
|
134
|
+
/** The MeshColliders given to this node's mesh objects: on its own mesh, or on a placed model's, as overrides of its children. */
|
|
135
|
+
writeMeshColliders(n, e) {
|
|
136
|
+
for (const { path, collider, layer } of this.meshColliders.get(n) ?? []) {
|
|
137
|
+
let at = e;
|
|
138
|
+
for (const name of path) {
|
|
139
|
+
let child = at.children.find((c) => c.tag === 'GameObject' && c.get('name') === name);
|
|
140
|
+
if (!child)
|
|
141
|
+
at.add((child = new El('GameObject').set('name', name)));
|
|
142
|
+
at = child;
|
|
143
|
+
}
|
|
144
|
+
if (layer && path.length)
|
|
145
|
+
at.set('layer', String(layer));
|
|
146
|
+
at.add(collider);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The physics package's MeshCollider as Unity's, which takes the mesh of its own object: one on every
|
|
151
|
+
* mesh under the node, as SceNoCo's gathers them — a placed model's on its own objects, under the
|
|
152
|
+
* scale that unpacks a compressed glTF. A Rigidbody above takes them all, as it takes child colliders.
|
|
153
|
+
*/
|
|
154
|
+
meshCollider(c, n, where) {
|
|
155
|
+
const collider = this.physics(c, where);
|
|
156
|
+
let found = 0;
|
|
157
|
+
const add = (node, path) => {
|
|
158
|
+
const list = this.meshColliders.get(node) ?? [];
|
|
159
|
+
list.push({ path, collider: copy(collider), layer: n.layer });
|
|
160
|
+
this.meshColliders.set(node, list);
|
|
161
|
+
found++;
|
|
162
|
+
};
|
|
163
|
+
const visit = (node) => {
|
|
164
|
+
if (node.mesh)
|
|
165
|
+
add(node, []);
|
|
166
|
+
for (const path of node.meshNodes ?? [])
|
|
167
|
+
add(node, path);
|
|
168
|
+
// A game prefab placed under it brings colliders of its own.
|
|
169
|
+
if (!node.prefab || node.meshNodes)
|
|
170
|
+
node.children.forEach(visit);
|
|
171
|
+
};
|
|
172
|
+
visit(n);
|
|
173
|
+
if (!found)
|
|
174
|
+
this.warn(where, 'MeshCollider: no mesh under it — left off.');
|
|
175
|
+
}
|
|
176
|
+
/** A node's Transform: each value that differs from `from`'s (a prefab's), or from a new object's. */
|
|
177
|
+
transform(n, from) {
|
|
178
|
+
const t = new El('Transform');
|
|
179
|
+
const differs = (a, b, fresh) => (b ? vec(a) !== vec(b) : a.some((v) => v !== fresh));
|
|
180
|
+
if (differs(n.position, from?.position, 0))
|
|
181
|
+
t.set('localPosition', vec(n.position));
|
|
182
|
+
const euler = eulerAngles(n.rotation);
|
|
183
|
+
if (differs(euler, from && eulerAngles(from.rotation), 0))
|
|
184
|
+
t.set('localEulerAngles', vec(euler));
|
|
185
|
+
if (differs(n.scale, from?.scale, 1))
|
|
186
|
+
t.set('localScale', vec(n.scale));
|
|
187
|
+
return t;
|
|
188
|
+
}
|
|
189
|
+
/** What a node's object holds besides its Transform and children: renderer, light, camera, components. */
|
|
190
|
+
own(n, off, scene) {
|
|
191
|
+
const e = new El('own');
|
|
192
|
+
if (n.mesh || n.materials) {
|
|
193
|
+
const filter = new El('MeshFilter');
|
|
194
|
+
if (n.mesh)
|
|
195
|
+
filter.set('sharedMesh', n.mesh);
|
|
196
|
+
e.add(filter);
|
|
197
|
+
const renderer = new El('MeshRenderer');
|
|
198
|
+
const materials = n.materials ?? [];
|
|
199
|
+
if (materials.length === 1)
|
|
200
|
+
renderer.set('sharedMaterial', materials[0]);
|
|
201
|
+
else if (materials.length > 1)
|
|
202
|
+
renderer.set('sharedMaterials', list(materials));
|
|
203
|
+
if (n.castShadows === false)
|
|
204
|
+
renderer.set('shadowCastingMode', 'Off');
|
|
205
|
+
if (n.receiveShadows === false)
|
|
206
|
+
renderer.set('receiveShadows', 'false');
|
|
207
|
+
if (off)
|
|
208
|
+
renderer.set('enabled', 'false');
|
|
209
|
+
e.add(renderer);
|
|
210
|
+
}
|
|
211
|
+
if (n.light) {
|
|
212
|
+
const l = n.light;
|
|
213
|
+
const light = new El('Light').set('type', l.type).set('color', l.color).set('intensity', num(l.intensity));
|
|
214
|
+
if (l.shadows)
|
|
215
|
+
light.set('shadows', 'Soft');
|
|
216
|
+
if (l.range !== undefined)
|
|
217
|
+
light.set('range', num(l.range));
|
|
218
|
+
if (l.spotAngle !== undefined)
|
|
219
|
+
light.set('spotAngle', num(l.spotAngle));
|
|
220
|
+
if (l.innerSpotAngle !== undefined)
|
|
221
|
+
light.set('innerSpotAngle', num(l.innerSpotAngle));
|
|
222
|
+
e.add(light);
|
|
223
|
+
}
|
|
224
|
+
if (n.camera) {
|
|
225
|
+
const c = n.camera;
|
|
226
|
+
const camera = new El('Camera');
|
|
227
|
+
if (c.orthographic)
|
|
228
|
+
camera.set('orthographic', 'true');
|
|
229
|
+
camera.set('nearClipPlane', num(c.near)).set('farClipPlane', num(c.far));
|
|
230
|
+
if (c.orthographic)
|
|
231
|
+
camera.set('orthographicSize', num(c.size ?? 5));
|
|
232
|
+
else
|
|
233
|
+
camera.set('fieldOfView', num(c.fov ?? 60));
|
|
234
|
+
if (scene.background)
|
|
235
|
+
camera.set('clearFlags', 'SolidColor').set('backgroundColor', scene.background);
|
|
236
|
+
e.add(camera);
|
|
237
|
+
// Post Processing on for every camera of a game with a Volume: one kept across loads shapes every level.
|
|
238
|
+
if (this.volumes)
|
|
239
|
+
e.add(new El('UniversalAdditionalCameraData').set('renderPostProcessing', 'true'));
|
|
240
|
+
}
|
|
241
|
+
for (const c of n.components)
|
|
242
|
+
this.component(c, n, e, off);
|
|
243
|
+
return e.children;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* How a copy differs from its prefab, as Unity's overrides on a placement: values of the object and of
|
|
247
|
+
* each component (the n-th of its type), components and children it adds, and the ones it lacks. A child
|
|
248
|
+
* is the prefab's child of its name. A reference inside the copy is the same as the prefab's when it
|
|
249
|
+
* points at the same place in each.
|
|
250
|
+
*/
|
|
251
|
+
overrides(i, p, e, path, root, scene, hidden) {
|
|
252
|
+
if ((i.layer ?? 0) !== (p.layer ?? 0))
|
|
253
|
+
e.set('layer', String(i.layer ?? 0));
|
|
254
|
+
if (i.active !== p.active)
|
|
255
|
+
e.set('m_IsActive', String(i.active));
|
|
256
|
+
const off = hidden || !i.renderersEnabled;
|
|
257
|
+
const mine = this.compared(root, () => this.own(i, off, scene));
|
|
258
|
+
const theirs = this.compared('', () => this.own(p, !p.renderersEnabled, {}));
|
|
259
|
+
// Written as this file writes them; what it can't say here is said only for a value that differs.
|
|
260
|
+
const warned = this.warnings.length;
|
|
261
|
+
const written = this.own(i, off, scene);
|
|
262
|
+
this.warnings.length = warned;
|
|
263
|
+
const removed = [];
|
|
264
|
+
const nth = (list, at) => list.slice(0, at).filter((x) => x.tag === list[at].tag).length;
|
|
265
|
+
const used = new Set();
|
|
266
|
+
mine.forEach((m, k) => {
|
|
267
|
+
const at = theirs.findIndex((t, x) => !used.has(x) && t.tag === m.tag && nth(theirs, x) === nth(mine, k));
|
|
268
|
+
if (at < 0)
|
|
269
|
+
return void e.add(written[k]); // a component the prefab lacks
|
|
270
|
+
used.add(at);
|
|
271
|
+
const t = theirs[at];
|
|
272
|
+
const diff = new El(m.tag);
|
|
273
|
+
for (const [key, value] of m.attrs) {
|
|
274
|
+
if (t.get(key) === value)
|
|
275
|
+
continue;
|
|
276
|
+
const text = written[k].get(key);
|
|
277
|
+
if (text !== undefined)
|
|
278
|
+
diff.set(key, text);
|
|
279
|
+
else
|
|
280
|
+
this.warn(i.source ?? `${this.holder} ${i.name}`, `${m.tag}.${key} on this copy points inside a placed prefab — set it in the prefab.`);
|
|
281
|
+
}
|
|
282
|
+
for (const [key] of t.attrs)
|
|
283
|
+
if (m.get(key) === undefined)
|
|
284
|
+
this.warn(i.source ?? `${this.holder} ${i.name}`, `${m.tag}.${key} is the prefab's own on this copy only by default — not written.`);
|
|
285
|
+
m.children.forEach((c, x) => {
|
|
286
|
+
if (print(c) !== (t.children.find((y) => y.tag === c.tag) ? print(t.children.find((y) => y.tag === c.tag)) : ''))
|
|
287
|
+
diff.add(written[k].children[x]);
|
|
288
|
+
});
|
|
289
|
+
if (diff.attrs.length || diff.children.length)
|
|
290
|
+
e.add(diff);
|
|
291
|
+
});
|
|
292
|
+
theirs.forEach((t, x) => void (!used.has(x) && t.tag !== 'GameObject' && removed.push(new El(t.tag))));
|
|
293
|
+
if (removed.length)
|
|
294
|
+
e.add(new El(`${e.tag}.removedComponents`).add(...removed));
|
|
295
|
+
const named = (list, name) => list.filter((c) => c.name === name);
|
|
296
|
+
const gone = [];
|
|
297
|
+
i.children.forEach((child, x) => {
|
|
298
|
+
const at = path === '' ? String(x) : `${path}/${x}`;
|
|
299
|
+
const same = named(p.children, child.name);
|
|
300
|
+
if (same.length === 0)
|
|
301
|
+
return void e.add(this.object(child, child.prefab ? 'PrefabInstance' : 'GameObject', at, scene, off));
|
|
302
|
+
const counterpart = same[named(i.children, child.name).indexOf(child)];
|
|
303
|
+
if (!counterpart)
|
|
304
|
+
return;
|
|
305
|
+
const el = new El('GameObject').set('name', child.name);
|
|
306
|
+
const transform = this.transform(child, counterpart);
|
|
307
|
+
if (transform.attrs.length)
|
|
308
|
+
el.add(transform);
|
|
309
|
+
this.overrides(child, counterpart, el, at, root, scene, off);
|
|
310
|
+
if (el.attrs.length + el.children.length === 1)
|
|
311
|
+
return;
|
|
312
|
+
if (same.length > 1)
|
|
313
|
+
return this.warn(child.source ?? `${this.holder} ${child.name}`, `this copy changes ${p.name}'s child "${child.name}", one of ${same.length} of that name — an override can't tell them apart: name them.`);
|
|
314
|
+
e.add(el);
|
|
315
|
+
});
|
|
316
|
+
for (const name of new Set(p.children.map((c) => c.name)))
|
|
317
|
+
for (let k = named(i.children, name).length; k < named(p.children, name).length; k++)
|
|
318
|
+
gone.push(new El('GameObject').set('name', name));
|
|
319
|
+
if (gone.length)
|
|
320
|
+
e.add(new El(`${e.tag}.removedGameObjects`).add(...gone));
|
|
321
|
+
}
|
|
322
|
+
/** Elements written for comparing: references relative to `root`, and nothing else recorded. */
|
|
323
|
+
compared(root, write) {
|
|
324
|
+
const warned = this.warnings.length;
|
|
325
|
+
const assets = { ...this.assets, volumes: [...this.assets.volumes] };
|
|
326
|
+
this.comparing = root;
|
|
327
|
+
try {
|
|
328
|
+
return write();
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
this.comparing = null;
|
|
332
|
+
this.warnings.length = warned;
|
|
333
|
+
this.assets.volumes = assets.volumes;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/** Tag the first camera under `e` MainCamera; false when it has none. */
|
|
337
|
+
tagMainCamera(e) {
|
|
338
|
+
if (e.children.some((c) => c.tag === 'Camera')) {
|
|
339
|
+
e.attrs.splice(e.attrs.findIndex(([k]) => k === 'name') + 1, 0, ['tag', 'MainCamera']);
|
|
340
|
+
if (!e.children.some((c) => c.tag === 'AudioListener'))
|
|
341
|
+
e.children.splice(e.children.findIndex((c) => c.tag === 'Camera') + 1, 0, new El('AudioListener'));
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
return e.children.some((c) => (c.tag === 'GameObject' ? this.tagMainCamera(c) : false));
|
|
345
|
+
}
|
|
346
|
+
warn(where, what) {
|
|
347
|
+
this.warnings.push(`${where}: ${what}`);
|
|
348
|
+
}
|
|
349
|
+
where(c, n) {
|
|
350
|
+
return c.source ?? n.source ?? `${this.holder} ${n.name}`;
|
|
351
|
+
}
|
|
352
|
+
// --- components --------------------------------------------------------------------------------
|
|
353
|
+
component(c, n, e, off) {
|
|
354
|
+
const where = this.where(c, n);
|
|
355
|
+
if (c.game)
|
|
356
|
+
return void e.add(this.behaviour(c, where));
|
|
357
|
+
if (c.type === 'MeshCollider')
|
|
358
|
+
return this.meshCollider(c, n, where);
|
|
359
|
+
if (c.type in PHYSICS)
|
|
360
|
+
return void e.add(this.physics(c, where));
|
|
361
|
+
switch (c.type) {
|
|
362
|
+
case 'ParticleSystem':
|
|
363
|
+
return this.particles(c, e, off, where);
|
|
364
|
+
case 'UIDocument':
|
|
365
|
+
return this.document(c, n, e, where);
|
|
366
|
+
case 'Terrain':
|
|
367
|
+
case 'TerrainCollider':
|
|
368
|
+
return this.terrain(c, e, where);
|
|
369
|
+
case 'Volume':
|
|
370
|
+
return this.volume(n, e);
|
|
371
|
+
case 'AudioSource':
|
|
372
|
+
return void e.add(this.audioSource(c, where));
|
|
373
|
+
case 'SplineContainer':
|
|
374
|
+
return this.splineContainer(c, n, e, where);
|
|
375
|
+
case 'SplineInstantiate':
|
|
376
|
+
return void e.add(this.splineInstantiate(c, where));
|
|
377
|
+
case 'SplineExtrude':
|
|
378
|
+
return void e.add(this.splineExtrude(c, n, where));
|
|
379
|
+
case 'SplineMesh':
|
|
380
|
+
return void e.add(this.splineMesh(c, where));
|
|
381
|
+
case 'SplineAnimate':
|
|
382
|
+
return void e.add(this.splineAnimate(c, where));
|
|
383
|
+
}
|
|
384
|
+
if (EFFECTS.has(c.type))
|
|
385
|
+
return; // in its Volume's profile
|
|
386
|
+
this.warn(where, `${c.type} has no Unity counterpart here — left off.`);
|
|
387
|
+
}
|
|
388
|
+
// --- audio and splines: the packages' components are Unity's own, by the same names -------------
|
|
389
|
+
/** The audio package's AudioSource as Unity's: the same names, `spatial` as Unity's spatial blend. */
|
|
390
|
+
audioSource(c, where) {
|
|
391
|
+
const e = new El('AudioSource');
|
|
392
|
+
const f = c.fields;
|
|
393
|
+
if (f.clip && typeof f.clip === 'object' && 'asset' in f.clip)
|
|
394
|
+
e.set('clip', f.clip.asset);
|
|
395
|
+
for (const key of ['playOnAwake', 'loop', 'volume', 'pitch', 'minDistance', 'maxDistance']) {
|
|
396
|
+
const v = f[key];
|
|
397
|
+
if (typeof v === 'number' || typeof v === 'boolean')
|
|
398
|
+
e.set(key, String(v));
|
|
399
|
+
}
|
|
400
|
+
if (typeof f.spatial === 'boolean')
|
|
401
|
+
e.set('spatialBlend', f.spatial ? '1' : '0');
|
|
402
|
+
const known = new Set(['clip', 'playOnAwake', 'loop', 'volume', 'pitch', 'spatial', 'minDistance', 'maxDistance']);
|
|
403
|
+
const unknown = Object.keys(f).filter((k) => !known.has(k) && f[k] !== null);
|
|
404
|
+
if (unknown.length)
|
|
405
|
+
this.warn(where, `AudioSource: ${unknown.join(', ')} ${unknown.length > 1 ? 'have' : 'has'} no Unity counterpart — left out.`);
|
|
406
|
+
return e;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* The splines package's knots as Unity's spline: each knot with the tangents SceNoCo gives it — its own,
|
|
410
|
+
* or made smooth from its neighbours as Unity's AutoSmooth does — mirrored as positions, and kept as
|
|
411
|
+
* written (Unity's Broken mode), so both engines draw the same curve.
|
|
412
|
+
*/
|
|
413
|
+
splineContainer(c, n, holder, where) {
|
|
414
|
+
const e = new El('SplineContainer');
|
|
415
|
+
holder.add(e);
|
|
416
|
+
let knots = c.fields.knots;
|
|
417
|
+
if (knots && typeof knots === 'object' && 'node' in knots) {
|
|
418
|
+
// Knots that are nodes: the spline as they stand now, and SplineKnotNodes to follow them as they move.
|
|
419
|
+
const parent = this.nodeAt(knots.node);
|
|
420
|
+
const ref = this.ref(knots.node, where);
|
|
421
|
+
if (!parent || !ref)
|
|
422
|
+
return;
|
|
423
|
+
holder.add(new El('SplineKnotNodes').set('knots', ref));
|
|
424
|
+
const into = this.world(n).invert();
|
|
425
|
+
knots = { array: parent.children.map((k) => ({ v3: new Vector3().setFromMatrixPosition(into.clone().multiply(this.world(k))).toArray() })) };
|
|
426
|
+
}
|
|
427
|
+
if (!knots || typeof knots !== 'object' || !('array' in knots))
|
|
428
|
+
return;
|
|
429
|
+
const triple = (v) => v && typeof v === 'object' && 'array' in v && v.array.length === 3 && v.array.every((x) => typeof x === 'number') ? v.array : v && typeof v === 'object' && 'v3' in v ? flipBack(v.v3) : undefined;
|
|
430
|
+
const read = [];
|
|
431
|
+
for (const k of knots.array) {
|
|
432
|
+
const position = triple(k);
|
|
433
|
+
if (position)
|
|
434
|
+
read.push({ position });
|
|
435
|
+
else if (k && typeof k === 'object' && 'object' in k) {
|
|
436
|
+
const f = k.object.fields;
|
|
437
|
+
const p = triple(f.position);
|
|
438
|
+
if (p)
|
|
439
|
+
read.push({ position: p, tangentIn: triple(f.tangentIn), tangentOut: triple(f.tangentOut), roll: typeof f.roll === 'number' ? f.roll : undefined });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (read.length !== knots.array.length)
|
|
443
|
+
this.warn(where, 'SplineContainer: a knot that is neither a position nor knot fields — left out.');
|
|
444
|
+
const closed = c.fields.closed === true;
|
|
445
|
+
const count = read.length;
|
|
446
|
+
const at = (i) => read[closed ? (i + count) % count : Math.min(Math.max(i, 0), count - 1)].position;
|
|
447
|
+
const sub = (a, b) => a.map((x, i) => x - b[i]);
|
|
448
|
+
const len = (a) => Math.hypot(...a);
|
|
449
|
+
// SceNoCo's AutoSmooth: along the line from the knot before to the one after, a third of the way to each.
|
|
450
|
+
const smooth = (i, side) => {
|
|
451
|
+
if (!closed && (side === 'in' ? i === 0 : i === count - 1))
|
|
452
|
+
return [0, 0, 0];
|
|
453
|
+
const d = sub(at(i + 1), at(i - 1));
|
|
454
|
+
const l = len(d) || 1;
|
|
455
|
+
const reach = side === 'out' ? len(sub(at(i + 1), at(i))) / 3 : -len(sub(at(i), at(i - 1))) / 3;
|
|
456
|
+
return d.map((x) => (x / l) * reach);
|
|
457
|
+
};
|
|
458
|
+
const neg = (a) => a.map((x) => -x);
|
|
459
|
+
const float3 = (tag, [x, y, z]) => new El(`BezierKnot.${tag}`).add(new El('float3').set('x', num(x)).set('y', num(y)).set('z', num(z)));
|
|
460
|
+
const list = new El('Spline.m_Knots');
|
|
461
|
+
// A roll banks the knot: Unity keeps it in the knot's Rotation, its tangents in the knot's own space.
|
|
462
|
+
const rolled = read.some((k) => k.roll);
|
|
463
|
+
read.forEach((k, i) => {
|
|
464
|
+
let out = mirror(k.tangentOut ?? (k.tangentIn ? neg(k.tangentIn) : smooth(i, 'out')));
|
|
465
|
+
let tin = mirror(k.tangentIn ?? (k.tangentOut ? neg(k.tangentOut) : smooth(i, 'in')));
|
|
466
|
+
const knot = new El('BezierKnot').add(float3('Position', mirror(k.position)));
|
|
467
|
+
if (rolled) {
|
|
468
|
+
const rotation = knotRotation(out, tin, k.roll ?? 0);
|
|
469
|
+
const inverse = rotation.clone().invert();
|
|
470
|
+
const local = (t) => new Vector3(...t).applyQuaternion(inverse).toArray();
|
|
471
|
+
[out, tin] = [local(out), local(tin)];
|
|
472
|
+
knot.add(new El('BezierKnot.Rotation').add(new El('quaternion').add(new El('quaternion.value').add(new El('float4').set('x', num(rotation.x)).set('y', num(rotation.y)).set('z', num(rotation.z)).set('w', num(rotation.w))))));
|
|
473
|
+
}
|
|
474
|
+
list.add(knot.add(float3('TangentIn', tin), float3('TangentOut', out)));
|
|
475
|
+
});
|
|
476
|
+
e.add(new El('SplineContainer.m_Splines').add(new El('Spline').set('m_Closed', String(closed)).add(list)));
|
|
477
|
+
}
|
|
478
|
+
/** The node at a path of child indices in this file, as `ref` finds it. */
|
|
479
|
+
nodeAt(path) {
|
|
480
|
+
const steps = path === '' ? [] : path.split('/').map(Number);
|
|
481
|
+
let node = this.roots.length === 1 && this.holder.endsWith('.prefab') ? this.roots[0] : undefined;
|
|
482
|
+
if (!node)
|
|
483
|
+
node = this.roots[steps.shift() ?? -1];
|
|
484
|
+
for (const i of steps)
|
|
485
|
+
node = node?.prefab ? undefined : node?.children[i];
|
|
486
|
+
return node;
|
|
487
|
+
}
|
|
488
|
+
/** A node's place in this file's space, in Unity's coordinates. */
|
|
489
|
+
world(n) {
|
|
490
|
+
const own = new Matrix4().compose(new Vector3(...n.position), new Quaternion(...n.rotation), new Vector3(...n.scale));
|
|
491
|
+
const parent = this.parents.get(n);
|
|
492
|
+
return parent ? this.world(parent).multiply(own) : own;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* The splines package's SplineInstantiate as Unity's: one item every `spacing`, offset in the spline's
|
|
496
|
+
* frame. Unity picks among several items by chance where SceNoCo takes turns, and places its copies itself.
|
|
497
|
+
*/
|
|
498
|
+
splineInstantiate(c, where) {
|
|
499
|
+
const e = new El('SplineInstantiate');
|
|
500
|
+
const f = c.fields;
|
|
501
|
+
if (f.container && typeof f.container === 'object' && 'node' in f.container) {
|
|
502
|
+
const ref = this.ref(f.container.node, where);
|
|
503
|
+
if (ref)
|
|
504
|
+
e.set('m_Container', ref);
|
|
505
|
+
}
|
|
506
|
+
const items = f.itemsToInstantiate && typeof f.itemsToInstantiate === 'object' && 'array' in f.itemsToInstantiate ? f.itemsToInstantiate.array : [];
|
|
507
|
+
if (items.length > 1)
|
|
508
|
+
this.warn(where, 'SplineInstantiate: Unity picks among several items by chance; SceNoCo takes turns.');
|
|
509
|
+
const list = new El('SplineInstantiate.m_ItemsToInstantiate');
|
|
510
|
+
for (const item of items)
|
|
511
|
+
if (item && typeof item === 'object' && 'asset' in item)
|
|
512
|
+
list.add(new El('InstantiableItem').set('Prefab', item.asset).set('Probability', '100'));
|
|
513
|
+
e.add(list);
|
|
514
|
+
const method = f.method === 'instanceCount' ? 'InstanceCount' : 'SpacingDistance';
|
|
515
|
+
e.set('m_Method', method);
|
|
516
|
+
if (method === 'InstanceCount' && typeof f.instanceCount === 'number')
|
|
517
|
+
e.set('m_Spacing', vec([f.instanceCount, f.instanceCount]));
|
|
518
|
+
else
|
|
519
|
+
e.set('m_Spacing', vec([typeof f.spacing === 'number' ? f.spacing : 2, typeof f.spacing === 'number' ? f.spacing : 2]));
|
|
520
|
+
e.set('m_Space', f.alignTo === 'world' ? 'World' : 'Spline');
|
|
521
|
+
// In the spline's frame — right, up, along — which mirrors with the world: the numbers stay as written.
|
|
522
|
+
const offset = f.positionOffset && typeof f.positionOffset === 'object' && 'v3' in f.positionOffset ? flipBack(f.positionOffset.v3) : undefined;
|
|
523
|
+
if (offset && offset.some((x) => x !== 0))
|
|
524
|
+
e.add(new El('SplineInstantiate.m_PositionOffset').add(new El('Vector3Offset').set('setup', 'HasOffset').set('min', vec(offset)).set('max', vec(offset))));
|
|
525
|
+
if (f.rotationOffset && typeof f.rotationOffset === 'object' && 'quat' in f.rotationOffset && f.rotationOffset.quat.slice(0, 3).some((x) => x !== 0))
|
|
526
|
+
this.warn(where, 'SplineInstantiate: rotationOffset is not exported — set it in Unity.');
|
|
527
|
+
// The same copies on every load: Unity seeds its choices, and picks a random seed of its own for 0.
|
|
528
|
+
e.set('m_Seed', '1');
|
|
529
|
+
return e;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* The splines package's SplineExtrude as Unity's, which it builds vertex for vertex. Unity extrudes
|
|
533
|
+
* in the container's own space, where SceNoCo reads the spline into the mesh's: the same only when
|
|
534
|
+
* the two nodes sit in one place.
|
|
535
|
+
*/
|
|
536
|
+
splineExtrude(c, n, where) {
|
|
537
|
+
const e = new El('SplineExtrude');
|
|
538
|
+
const f = c.fields;
|
|
539
|
+
const holder = f.container && typeof f.container === 'object' && 'node' in f.container ? f.container.node : undefined;
|
|
540
|
+
if (holder) {
|
|
541
|
+
const ref = this.ref(holder, where);
|
|
542
|
+
if (ref)
|
|
543
|
+
e.set('m_Container', ref);
|
|
544
|
+
const other = this.nodeAt(holder);
|
|
545
|
+
if (other && !this.world(other).equals(this.world(n)))
|
|
546
|
+
this.warn(where, 'SplineExtrude: Unity builds in the container node\'s space — put the mesh where its container is, or the road lands offset.');
|
|
547
|
+
}
|
|
548
|
+
const shape = f.shape === 'square' ? 'Square' : f.shape === 'road' ? 'Road' : 'Circle';
|
|
549
|
+
const shapeEl = new El(shape);
|
|
550
|
+
if (shape === 'Circle' && typeof f.sides === 'number')
|
|
551
|
+
shapeEl.set('m_Sides', String(f.sides));
|
|
552
|
+
e.add(new El('SplineExtrude.m_Shape').add(shapeEl));
|
|
553
|
+
if (typeof f.sides === 'number')
|
|
554
|
+
e.set('m_Sides', String(f.sides));
|
|
555
|
+
for (const [key, field] of [['segmentsPerUnit', 'm_SegmentsPerUnit'], ['capped', 'm_Capped'], ['radius', 'm_Radius'], ['flipNormals', 'm_FlipNormals']]) {
|
|
556
|
+
const v = f[key];
|
|
557
|
+
if (typeof v === 'number' || typeof v === 'boolean')
|
|
558
|
+
e.set(field, String(v));
|
|
559
|
+
}
|
|
560
|
+
if (f.range && typeof f.range === 'object' && 'v2' in f.range)
|
|
561
|
+
e.set('m_Range', vec(f.range.v2));
|
|
562
|
+
return e;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* The splines package's SplineMesh, which Unity lacks, as SceNoCo's own port of it (SplineMesh.cs,
|
|
566
|
+
* copied with the export): the same piece bent the same way, a model keeping its materials.
|
|
567
|
+
*/
|
|
568
|
+
splineMesh(c, where) {
|
|
569
|
+
const e = new El('SplineMesh');
|
|
570
|
+
const f = c.fields;
|
|
571
|
+
if (f.container && typeof f.container === 'object' && 'node' in f.container) {
|
|
572
|
+
const ref = this.ref(f.container.node, where);
|
|
573
|
+
if (ref)
|
|
574
|
+
e.set('container', ref);
|
|
575
|
+
}
|
|
576
|
+
if (f.mesh && typeof f.mesh === 'object' && 'asset' in f.mesh)
|
|
577
|
+
e.set('mesh', f.mesh.asset);
|
|
578
|
+
else
|
|
579
|
+
this.warn(where, 'SplineMesh: its mesh is not a model file or a mesh the export writes — set it in Unity.');
|
|
580
|
+
if (typeof f.count === 'number' && f.count > 0)
|
|
581
|
+
e.set('count', String(f.count));
|
|
582
|
+
return e;
|
|
583
|
+
}
|
|
584
|
+
/** The splines package's SplineAnimate as Unity's: the same settings, with the node's +Z along the spline and +Y up. */
|
|
585
|
+
splineAnimate(c, where) {
|
|
586
|
+
const e = new El('SplineAnimate');
|
|
587
|
+
const f = c.fields;
|
|
588
|
+
if (f.container && typeof f.container === 'object' && 'node' in f.container) {
|
|
589
|
+
const ref = this.ref(f.container.node, where);
|
|
590
|
+
if (ref)
|
|
591
|
+
e.set('m_Target', ref);
|
|
592
|
+
}
|
|
593
|
+
else
|
|
594
|
+
this.warn(where, 'SplineAnimate: Unity needs its container named — give it container={…}.');
|
|
595
|
+
if (f.animationMethod === 'speed')
|
|
596
|
+
e.set('m_Method', 'Speed');
|
|
597
|
+
const loop = { once: 'Once', loopContinuous: 'Loop', pingPong: 'PingPong' }[f.loop];
|
|
598
|
+
if (loop)
|
|
599
|
+
e.set('m_LoopMode', loop);
|
|
600
|
+
if (f.alignment === 'none')
|
|
601
|
+
e.set('m_AlignmentMode', 'None');
|
|
602
|
+
for (const [key, field] of [['duration', 'm_Duration'], ['maxSpeed', 'm_MaxSpeed'], ['playOnAwake', 'm_PlayOnAwake'], ['startOffset', 'm_StartOffset']]) {
|
|
603
|
+
const v = f[key];
|
|
604
|
+
if (typeof v === 'number' || typeof v === 'boolean')
|
|
605
|
+
e.set(field, String(v));
|
|
606
|
+
}
|
|
607
|
+
return e;
|
|
608
|
+
}
|
|
609
|
+
/** A game behaviour: its serialized fields by name, each only where its C# class declares it. */
|
|
610
|
+
behaviour(c, where) {
|
|
611
|
+
const e = new El(c.type);
|
|
612
|
+
for (const [field, v] of Object.entries(c.fields)) {
|
|
613
|
+
if (v === null)
|
|
614
|
+
continue;
|
|
615
|
+
if (this.options.declares && !this.options.declares(c.type, field)) {
|
|
616
|
+
this.warn(where, `${c.type} has no serialized field ${field} — add a public one to wire it, and export again.`);
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
this.value(e, field, v, where);
|
|
620
|
+
}
|
|
621
|
+
return e;
|
|
622
|
+
}
|
|
623
|
+
/** One value as an attribute, or as a property element when it is a list of what text can't hold. */
|
|
624
|
+
value(e, name, v, where) {
|
|
625
|
+
const text = this.text(v, where);
|
|
626
|
+
if (text !== undefined)
|
|
627
|
+
return void e.set(name, text);
|
|
628
|
+
if (v && typeof v === 'object' && 'array' in v) {
|
|
629
|
+
const items = v.array.map((item) => this.item(item, where)).filter((x) => !!x);
|
|
630
|
+
if (items.length === v.array.length)
|
|
631
|
+
return void e.add(new El(`${e.tag}.${name}`).add(...items));
|
|
632
|
+
}
|
|
633
|
+
if (v && typeof v === 'object' && 'object' in v)
|
|
634
|
+
return void e.add(new El(`${e.tag}.${name}`).add(this.struct(v.object.type, v.object.fields, where)));
|
|
635
|
+
this.warn(where, `${e.tag}.${name} could not be written — left out.`);
|
|
636
|
+
}
|
|
637
|
+
/** A value as attribute text, or undefined when it is structured (or a reference that could not be found). */
|
|
638
|
+
text(v, where) {
|
|
639
|
+
if (v === null)
|
|
640
|
+
return undefined;
|
|
641
|
+
if (typeof v === 'number')
|
|
642
|
+
return num(v);
|
|
643
|
+
if (typeof v === 'boolean' || typeof v === 'string')
|
|
644
|
+
return String(v);
|
|
645
|
+
if ('v2' in v)
|
|
646
|
+
return vec(v.v2);
|
|
647
|
+
if ('v3' in v)
|
|
648
|
+
return vec(v.v3);
|
|
649
|
+
if ('v4' in v)
|
|
650
|
+
return vec(v.v4);
|
|
651
|
+
if ('quat' in v)
|
|
652
|
+
return vec(v.quat);
|
|
653
|
+
if ('color' in v)
|
|
654
|
+
return v.color;
|
|
655
|
+
if ('asset' in v) {
|
|
656
|
+
if (v.asset === this.holder && this.comparing === null) {
|
|
657
|
+
this.warn(where, `holds its own prefab: in Unity a prefab's reference to itself is, on each copy, that copy — Instantiate clones the live object, not the asset.`);
|
|
658
|
+
// As Unity keeps it, and Scenoco writes it: the prefab's root, by reference.
|
|
659
|
+
return this.ref('', where);
|
|
660
|
+
}
|
|
661
|
+
return v.asset;
|
|
662
|
+
}
|
|
663
|
+
if ('node' in v)
|
|
664
|
+
return this.ref(v.node, where, 'component' in v ? v.component : undefined);
|
|
665
|
+
if ('array' in v) {
|
|
666
|
+
// Lists of numbers or references are one attribute; anything else is items.
|
|
667
|
+
const items = v.array.map((x) => (typeof x === 'number' || typeof x === 'boolean' ? String(x) : x && typeof x === 'object' && ('asset' in x || 'node' in x) ? this.text(x, where) : undefined));
|
|
668
|
+
if (items.some((x) => x === undefined))
|
|
669
|
+
return undefined;
|
|
670
|
+
return list(items);
|
|
671
|
+
}
|
|
672
|
+
return undefined;
|
|
673
|
+
}
|
|
674
|
+
item(v, where) {
|
|
675
|
+
if (v === null)
|
|
676
|
+
return undefined;
|
|
677
|
+
const t = typeof v === 'string' ? 'String' : typeof v === 'number' ? 'Single' : typeof v === 'boolean' ? 'Boolean'
|
|
678
|
+
: 'v2' in v ? 'Vector2' : 'v3' in v ? 'Vector3' : 'v4' in v ? 'Vector4' : 'quat' in v ? 'Quaternion' : 'color' in v ? 'Color' : undefined;
|
|
679
|
+
if (t)
|
|
680
|
+
return new El(t).set('value', this.text(v, where));
|
|
681
|
+
if (typeof v === 'object' && 'object' in v)
|
|
682
|
+
return this.struct(v.object.type, v.object.fields, where);
|
|
683
|
+
return undefined;
|
|
684
|
+
}
|
|
685
|
+
struct(type, fields, where) {
|
|
686
|
+
const e = new El(type);
|
|
687
|
+
for (const [k, f] of Object.entries(fields))
|
|
688
|
+
if (f !== null)
|
|
689
|
+
this.value(e, k, f, where);
|
|
690
|
+
return e;
|
|
691
|
+
}
|
|
692
|
+
/** A node of this file by its path of child indices: `#Name`, or `#id` given to its element. */
|
|
693
|
+
ref(path, where, component) {
|
|
694
|
+
if (this.comparing !== null) {
|
|
695
|
+
const root = this.comparing;
|
|
696
|
+
if (root === '' || path === root)
|
|
697
|
+
return `@${root === '' ? path : ''}`;
|
|
698
|
+
return path.startsWith(`${root}/`) ? `@${path.slice(root.length + 1)}` : `@@${path}`;
|
|
699
|
+
}
|
|
700
|
+
const steps = path === '' ? [] : path.split('/').map(Number);
|
|
701
|
+
let node = this.roots.length === 1 && this.holder.endsWith('.prefab') ? this.roots[0] : undefined;
|
|
702
|
+
if (!node)
|
|
703
|
+
node = this.roots[steps.shift() ?? -1];
|
|
704
|
+
for (const [k, i] of steps.entries()) {
|
|
705
|
+
// Inside a placed prefab, past its root: what it holds is the prefab's, no element here.
|
|
706
|
+
if (node?.prefab && k < steps.length)
|
|
707
|
+
node = undefined;
|
|
708
|
+
else
|
|
709
|
+
node = node?.children[i];
|
|
710
|
+
}
|
|
711
|
+
if (!node) {
|
|
712
|
+
this.warn(where, `a reference to ${path || 'the root'} is inside a placed prefab — set it in that prefab instead.`);
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
// Unity's text names a component by its object, the field's type picking it: two of one type can't be told apart.
|
|
716
|
+
const same = component ? node.components.filter((c) => c.type === component).length : 0;
|
|
717
|
+
if (same > 1)
|
|
718
|
+
this.warn(where, `a reference to one of the ${same} ${component}s on "${node.name}" — Unity's can't say which: put each on an object of its own.`);
|
|
719
|
+
const known = this.refs.get(node);
|
|
720
|
+
if (known)
|
|
721
|
+
return known;
|
|
722
|
+
let ref;
|
|
723
|
+
if ((this.names.get(node.name) ?? 0) === 1 && !/[/#,\s]/.test(node.name))
|
|
724
|
+
ref = `#${node.name}`;
|
|
725
|
+
else {
|
|
726
|
+
const base = node.name.replace(/[^\w-]+/g, '_') || 'Object';
|
|
727
|
+
let id = base;
|
|
728
|
+
for (let k = 2; this.ids.has(id) || this.names.has(id); k++)
|
|
729
|
+
id = `${base}_${k}`;
|
|
730
|
+
this.ids.add(id);
|
|
731
|
+
ref = `#${id}`;
|
|
732
|
+
// Given to its element once the file is written (finish): it may come before or after this reference.
|
|
733
|
+
this.idsByNode.set(node, id);
|
|
734
|
+
}
|
|
735
|
+
this.refs.set(node, ref);
|
|
736
|
+
return ref;
|
|
737
|
+
}
|
|
738
|
+
// --- physics: SceNoCo's rapier and box2d components are Unity's own, by the same names --------
|
|
739
|
+
physics(c, where) {
|
|
740
|
+
const spec = PHYSICS[c.type];
|
|
741
|
+
const f = c.fields;
|
|
742
|
+
const e = new El(c.type);
|
|
743
|
+
const unknown = Object.keys(f).filter((k) => !spec.fields.includes(k) && !SURFACE.has(k) && k !== 'layer' && f[k] !== null);
|
|
744
|
+
if (unknown.length)
|
|
745
|
+
this.warn(where, `${c.type}: ${unknown.join(', ')} ${unknown.length > 1 ? 'have' : 'has'} no Unity counterpart — left out.`);
|
|
746
|
+
// Unity's setters in the order they need: a joint's auto anchor before its anchor, a body's auto mass before its mass.
|
|
747
|
+
for (const k of spec.fields) {
|
|
748
|
+
let v = k in f ? f[k] : k === 'autoConfigureConnectedAnchor' ? spec.autoAnchor ?? null : null;
|
|
749
|
+
if (v === null)
|
|
750
|
+
continue;
|
|
751
|
+
if (k === 'mass' && f.useAutoMass === true)
|
|
752
|
+
continue;
|
|
753
|
+
if (k === 'size' && spec.dimensions === 3 && typeof v === 'object' && 'v3' in v)
|
|
754
|
+
v = { v3: v.v3.map(Math.abs) };
|
|
755
|
+
const struct = spec.structs?.[k];
|
|
756
|
+
if (struct) {
|
|
757
|
+
// A struct's setter turns its switch on (motor → useMotor): written only where the switch is not off.
|
|
758
|
+
if (f[struct.switch] === false || typeof v !== 'object' || !('object' in v))
|
|
759
|
+
continue;
|
|
760
|
+
e.add(new El(`${c.type}.${k}`).add(this.struct(struct.type, v.object.fields, where)));
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (k === 'points' && typeof v === 'object' && 'array' in v) {
|
|
764
|
+
e.add(new El(`${c.type}.points`).add(...v.array.map((p) => new El('Vector2').set('value', this.text(p, where) ?? '0 0'))));
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
const text = this.text(v, where);
|
|
768
|
+
if (text !== undefined)
|
|
769
|
+
e.set(k, text);
|
|
770
|
+
}
|
|
771
|
+
const material = this.surface(c, spec.dimensions);
|
|
772
|
+
if (material)
|
|
773
|
+
e.set('sharedMaterial', material);
|
|
774
|
+
return e;
|
|
775
|
+
}
|
|
776
|
+
/** A collider's friction and bounciness — its own, or its shared material's — as one physics material asset per pair. */
|
|
777
|
+
surface(c, dimensions) {
|
|
778
|
+
const m = c.fields.material;
|
|
779
|
+
const s = m && typeof m === 'object' && 'object' in m ? m.object.fields : c.fields;
|
|
780
|
+
if (s.friction === undefined && s.bounciness === undefined)
|
|
781
|
+
return undefined;
|
|
782
|
+
const friction = typeof s.friction === 'number' ? s.friction : dimensions === 2 ? 0.4 : 0.5;
|
|
783
|
+
const bounciness = typeof s.bounciness === 'number' ? s.bounciness : 0;
|
|
784
|
+
const label = (n) => String(Math.round(n * 100) / 100);
|
|
785
|
+
const path = `Assets/Materials/Physics/Friction${label(friction)}_Bounce${label(bounciness)}${dimensions === 2 ? '_2D' : ''}.asset`;
|
|
786
|
+
if (!this.assets.physicsMaterials.some((p) => p.path === path))
|
|
787
|
+
this.assets.physicsMaterials.push({ path, dimensions, friction, bounciness });
|
|
788
|
+
return path;
|
|
789
|
+
}
|
|
790
|
+
// --- particles: three.quarks' effect as Unity's ParticleSystem, module by module --------------
|
|
791
|
+
particles(c, e, off, where) {
|
|
792
|
+
const effect = c.fields.effect;
|
|
793
|
+
if (!effect || typeof effect !== 'object' || !('object' in effect))
|
|
794
|
+
return this.warn(where, 'ParticleSystem has no effect it could read — left off.');
|
|
795
|
+
const f = effect.object.fields;
|
|
796
|
+
const n = (o, k, d) => (typeof o[k] === 'number' ? o[k] : d);
|
|
797
|
+
const sub = (k) => {
|
|
798
|
+
const v = f[k];
|
|
799
|
+
return v && typeof v === 'object' && 'object' in v ? v.object.fields : {};
|
|
800
|
+
};
|
|
801
|
+
const deg = Math.PI / 180;
|
|
802
|
+
const ps = new El('ParticleSystem');
|
|
803
|
+
const main = new El('MainModule')
|
|
804
|
+
.set('duration', num(n(f, 'duration', 5)))
|
|
805
|
+
.set('loop', String(f.looping !== false))
|
|
806
|
+
.set('prewarm', String(f.prewarm === true))
|
|
807
|
+
.set('startLifetime', num(n(f, 'startLifetime', 5)))
|
|
808
|
+
.set('startSpeed', num(n(f, 'startSpeed', 5)))
|
|
809
|
+
.set('startSize', num(n(f, 'startSize', 1)))
|
|
810
|
+
.set('startRotation', num(n(f, 'startRotation', 0) * deg))
|
|
811
|
+
.set('startColor', f.startColor && typeof f.startColor === 'object' && 'color' in f.startColor ? f.startColor.color : '#ffffff')
|
|
812
|
+
.set('gravityModifier', num(n(f, 'gravityModifier', 0)))
|
|
813
|
+
.set('simulationSpace', f.simulationSpace === 'World' ? 'World' : 'Local')
|
|
814
|
+
.set('scalingMode', 'Hierarchy')
|
|
815
|
+
.set('playOnAwake', String(c.fields.playOnAwake !== false));
|
|
816
|
+
ps.add(new El('ParticleSystem.main').add(main));
|
|
817
|
+
const em = sub('emission');
|
|
818
|
+
const emission = new El('EmissionModule').set('rateOverTime', num(n(em, 'rateOverTime', 10)));
|
|
819
|
+
const bursts = em.bursts && typeof em.bursts === 'object' && 'array' in em.bursts ? em.bursts.array : [];
|
|
820
|
+
if (bursts.length) {
|
|
821
|
+
emission.add(new El('EmissionModule.bursts').add(...bursts.map((b) => {
|
|
822
|
+
const bf = b && typeof b === 'object' && 'object' in b ? b.object.fields : {};
|
|
823
|
+
return new El('Burst').set('time', num(n(bf, 'time', 0))).set('count', num(Math.round(n(bf, 'count', 0))));
|
|
824
|
+
})));
|
|
825
|
+
}
|
|
826
|
+
ps.add(new El('ParticleSystem.emission').add(emission));
|
|
827
|
+
// three.quarks emits along +Z like Unity; the mirror on Z turns a cone or a hemisphere round.
|
|
828
|
+
const sh = sub('shape');
|
|
829
|
+
const type = typeof sh.type === 'string' ? sh.type : 'Cone';
|
|
830
|
+
const radius = n(sh, 'radius', 1);
|
|
831
|
+
const shape = new El('ShapeModule');
|
|
832
|
+
const shapeType = { Sphere: 'Sphere', Hemisphere: 'Hemisphere', Circle: 'Circle', Donut: 'Donut', Rectangle: 'Rectangle', Point: 'Sphere' }[type] ?? 'Cone';
|
|
833
|
+
shape.set('shapeType', shapeType).set('radius', num(type === 'Point' ? 0.0001 : radius)).set('angle', num(n(sh, 'angle', 25))).set('arc', num(n(sh, 'arc', 360)));
|
|
834
|
+
if (shapeType === 'Cone' || shapeType === 'Hemisphere')
|
|
835
|
+
shape.set('rotation', '0 180 0');
|
|
836
|
+
if (shapeType === 'Rectangle')
|
|
837
|
+
shape.set('scale', vec([radius * 2, radius * 2, 1]));
|
|
838
|
+
ps.add(new El('ParticleSystem.shape').add(shape));
|
|
839
|
+
if ('noise' in f) {
|
|
840
|
+
const no = sub('noise');
|
|
841
|
+
ps.add(new El('ParticleSystem.noise').add(new El('NoiseModule').set('enabled', 'true').set('strength', num(n(no, 'strength', 1))).set('frequency', num(n(no, 'frequency', 2)))));
|
|
842
|
+
}
|
|
843
|
+
const colorList = sub('colorOverLifetime').colors;
|
|
844
|
+
const colors = (colorList && typeof colorList === 'object' && 'array' in colorList ? colorList.array : [])
|
|
845
|
+
.map((x) => (x && typeof x === 'object' && 'color' in x ? x.color : null)).filter((x) => !!x).slice(0, 8);
|
|
846
|
+
if (colors.length) {
|
|
847
|
+
// Evenly spaced, as the effect writes them; full alpha, fading out over the last third, as three.quarks does.
|
|
848
|
+
const gradient = new El('MinMaxGradient.gradient').add(...colors.map((col, i) => new El('Color').set('time', num(colors.length === 1 ? 0 : i / (colors.length - 1))).set('value', col)), new El('Alpha').set('time', '0').set('value', '1'), new El('Alpha').set('time', '0.7').set('value', '1'), new El('Alpha').set('time', '1').set('value', '0'));
|
|
849
|
+
ps.add(new El('ParticleSystem.colorOverLifetime').add(new El('ColorOverLifetimeModule').set('enabled', 'true')
|
|
850
|
+
.add(new El('ColorOverLifetimeModule.color').add(new El('MinMaxGradient').set('mode', 'Gradient').add(gradient)))));
|
|
851
|
+
}
|
|
852
|
+
const sizeList = sub('sizeOverLifetime').curve;
|
|
853
|
+
const sizes = (sizeList && typeof sizeList === 'object' && 'array' in sizeList ? sizeList.array : []).filter((x) => typeof x === 'number');
|
|
854
|
+
if (sizes.length) {
|
|
855
|
+
// Linear between the values, as three.quarks reads them: each key's tangents are the slopes to its neighbours.
|
|
856
|
+
const at = (i) => (sizes.length === 1 ? 0 : i / (sizes.length - 1));
|
|
857
|
+
const slope = (a, b) => (b < 0 || b >= sizes.length || a < 0 ? 0 : (sizes[b] - sizes[a]) / (at(b) - at(a)));
|
|
858
|
+
const keys = sizes.map((v, i) => new El('Key').set('time', num(at(i))).set('value', num(v)).set('inTangent', num(slope(i - 1, i))).set('outTangent', num(slope(i, i + 1))));
|
|
859
|
+
ps.add(new El('ParticleSystem.sizeOverLifetime').add(new El('SizeOverLifetimeModule').set('enabled', 'true')
|
|
860
|
+
.add(new El('SizeOverLifetimeModule.size').add(new El('MinMaxCurve').set('mode', 'Curve').set('curveMultiplier', '1').add(new El('MinMaxCurve.curve').add(...keys))))));
|
|
861
|
+
}
|
|
862
|
+
if ('rotationOverLifetime' in f) {
|
|
863
|
+
ps.add(new El('ParticleSystem.rotationOverLifetime').add(new El('RotationOverLifetimeModule').set('enabled', 'true').set('z', num(n(sub('rotationOverLifetime'), 'angularVelocity', 0) * deg))));
|
|
864
|
+
}
|
|
865
|
+
e.add(ps);
|
|
866
|
+
const r = sub('renderer');
|
|
867
|
+
const renderMode = { StretchedBillboard: 'Stretch', HorizontalBillboard: 'HorizontalBillboard', VerticalBillboard: 'VerticalBillboard', Mesh: 'Mesh' }[String(r.renderMode)] ?? 'Billboard';
|
|
868
|
+
const blending = r.blending === 'Alpha' ? 'Alpha' : 'Additive';
|
|
869
|
+
if (!this.assets.particleMaterials.includes(blending))
|
|
870
|
+
this.assets.particleMaterials.push(blending);
|
|
871
|
+
const renderer = new El('ParticleSystemRenderer').set('renderMode', renderMode).set('sharedMaterial', `Assets/Materials/Particles-${blending}.mat`);
|
|
872
|
+
if (off)
|
|
873
|
+
renderer.set('enabled', 'false');
|
|
874
|
+
e.add(renderer);
|
|
875
|
+
}
|
|
876
|
+
// --- the page, terrains, post effects ----------------------------------------------------------
|
|
877
|
+
document(c, n, e, where) {
|
|
878
|
+
const element = typeof c.fields.element === 'string' ? c.fields.element : 'ui';
|
|
879
|
+
const documents = this.options.documents ?? {};
|
|
880
|
+
const uxml = documents[element];
|
|
881
|
+
if (!uxml)
|
|
882
|
+
return this.warn(where, `no UXML for the element "${element}" — the page has no element with that id.`);
|
|
883
|
+
const path = `Assets/UI/${element}.panel.asset`;
|
|
884
|
+
if (!this.assets.panels.some((p) => p.path === path)) {
|
|
885
|
+
const size = c.fields.referenceResolution;
|
|
886
|
+
this.assets.panels.push({
|
|
887
|
+
path,
|
|
888
|
+
referenceResolution: size && typeof size === 'object' && 'v2' in size ? size.v2 : [1280, 720],
|
|
889
|
+
match: typeof c.fields.match === 'number' ? c.fields.match : 0.5,
|
|
890
|
+
// In the page's order: an element written later draws over an earlier one.
|
|
891
|
+
sortingOrder: Object.keys(documents).indexOf(element),
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
const document = new El('UIDocument').set('panelSettings', path).set('visualTreeAsset', uxml);
|
|
895
|
+
// Unity takes one UIDocument an object: several on one node are each on a child named after its element.
|
|
896
|
+
if (n.components.filter((x) => x.type === 'UIDocument').length > 1)
|
|
897
|
+
e.add(new El('GameObject').set('name', element).add(document));
|
|
898
|
+
else
|
|
899
|
+
e.add(document);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* SceNoCo's terrain is centred on its node; Unity's starts at its object's corner, so the Terrain and
|
|
903
|
+
* its collider sit on a child named Terrain at the data's offset.
|
|
904
|
+
*/
|
|
905
|
+
terrain(c, e, where) {
|
|
906
|
+
const data = c.fields.terrainData;
|
|
907
|
+
const path = data && typeof data === 'object' && 'asset' in data ? data.asset : undefined;
|
|
908
|
+
const t = path ? this.terrains.get(path) : undefined;
|
|
909
|
+
if (!t)
|
|
910
|
+
return this.warn(where, `${c.type} has no exported terrainData — left off.`);
|
|
911
|
+
let child = e.children.find((x) => x.tag === 'GameObject' && x.get('name') === 'Terrain');
|
|
912
|
+
if (!child) {
|
|
913
|
+
child = new El('GameObject').set('name', 'Terrain').add(new El('Transform').set('localPosition', vec(t.offset)));
|
|
914
|
+
e.add(child);
|
|
915
|
+
}
|
|
916
|
+
if (c.type === 'Terrain') {
|
|
917
|
+
this.assets.terrainMaterial = 'Assets/Terrains/TerrainLit.mat';
|
|
918
|
+
const terrain = new El('Terrain').set('terrainData', t.path).set('materialTemplate', this.assets.terrainMaterial);
|
|
919
|
+
if (typeof c.fields.heightmapPixelError === 'number')
|
|
920
|
+
terrain.set('heightmapPixelError', num(c.fields.heightmapPixelError));
|
|
921
|
+
if (c.fields.castShadows === false)
|
|
922
|
+
terrain.set('shadowCastingMode', 'Off');
|
|
923
|
+
child.add(terrain);
|
|
924
|
+
}
|
|
925
|
+
else
|
|
926
|
+
child.add(new El('TerrainCollider').set('terrainData', t.path));
|
|
927
|
+
}
|
|
928
|
+
/** A URP Volume: global, with its profile — the node's effect components — as an asset the importer makes. */
|
|
929
|
+
volume(n, e) {
|
|
930
|
+
const volume = n.components.find((c) => c.type === 'Volume');
|
|
931
|
+
const base = n.name.replace(/[^\w-]+/g, '_') || 'Volume';
|
|
932
|
+
let path = `Assets/Materials/Volume-${base}.asset`;
|
|
933
|
+
for (let k = 2; this.assets.volumes.some((v) => v.path === path); k++)
|
|
934
|
+
path = `Assets/Materials/Volume-${base}-${k}.asset`;
|
|
935
|
+
this.assets.volumes.push({ path, effects: n.components.filter((c) => EFFECTS.has(c.type)).map((c) => ({ type: c.type, fields: c.fields })) });
|
|
936
|
+
const el = new El('Volume').set('isGlobal', 'true').set('sharedProfile', path);
|
|
937
|
+
if (typeof volume.fields.priority === 'number')
|
|
938
|
+
el.set('priority', num(volume.fields.priority));
|
|
939
|
+
e.add(el);
|
|
940
|
+
}
|
|
941
|
+
/** Give each referenced element its id, after its name: called once the file is written. */
|
|
942
|
+
finish() {
|
|
943
|
+
for (const [node, id] of this.idsByNode) {
|
|
944
|
+
const e = this.elements.get(node);
|
|
945
|
+
if (e)
|
|
946
|
+
e.attrs.splice(e.attrs.findIndex(([k]) => k === 'name') + 1, 0, ['id', id]);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
/** The post effects a Volume's profile holds: components of their own in SceNoCo, overrides in URP. */
|
|
951
|
+
const EFFECTS = new Set(['Bloom', 'Tonemapping', 'ColorAdjustments', 'Vignette', 'DepthOfField', 'ChromaticAberration', 'FilmGrain']);
|
|
952
|
+
/** A collider's surface, written as its physics material. */
|
|
953
|
+
const SURFACE = new Set(['friction', 'bounciness', 'material']);
|
|
954
|
+
const COLLIDER_3D = ['isTrigger'];
|
|
955
|
+
const COLLIDER_2D = ['isTrigger', 'offset', 'density'];
|
|
956
|
+
const JOINT = ['enableCollision', 'breakForce', 'breakTorque', 'connectedBody'];
|
|
957
|
+
const ANCHORED = [...JOINT, 'anchor', 'autoConfigureConnectedAnchor', 'connectedAnchor'];
|
|
958
|
+
const MOTOR = { motor: { type: 'JointMotor2D', switch: 'useMotor' } };
|
|
959
|
+
const PHYSICS = {
|
|
960
|
+
Rigidbody: { dimensions: 3, fields: ['isKinematic', 'useGravity', 'linearDamping', 'angularDamping', 'constraints', 'freezeRotation'] },
|
|
961
|
+
BoxCollider: { dimensions: 3, fields: [...COLLIDER_3D, 'size', 'center'] },
|
|
962
|
+
SphereCollider: { dimensions: 3, fields: [...COLLIDER_3D, 'radius', 'center'] },
|
|
963
|
+
CapsuleCollider: { dimensions: 3, fields: [...COLLIDER_3D, 'radius', 'height', 'center'] },
|
|
964
|
+
MeshCollider: { dimensions: 3, fields: ['convex', ...COLLIDER_3D] },
|
|
965
|
+
Rigidbody2D: { dimensions: 2, fields: ['bodyType', 'useAutoMass', 'mass', 'gravityScale', 'linearDamping', 'angularDamping', 'constraints', 'freezeRotation', 'collisionDetectionMode'] },
|
|
966
|
+
BoxCollider2D: { dimensions: 2, fields: [...COLLIDER_2D, 'size'] },
|
|
967
|
+
CircleCollider2D: { dimensions: 2, fields: [...COLLIDER_2D, 'radius'] },
|
|
968
|
+
CapsuleCollider2D: { dimensions: 2, fields: [...COLLIDER_2D, 'size', 'direction'] },
|
|
969
|
+
PolygonCollider2D: { dimensions: 2, fields: [...COLLIDER_2D, 'points'] },
|
|
970
|
+
EdgeCollider2D: { dimensions: 2, fields: [...COLLIDER_2D, 'points'] },
|
|
971
|
+
FixedJoint2D: { dimensions: 2, fields: [...ANCHORED, 'frequency', 'dampingRatio'] },
|
|
972
|
+
HingeJoint2D: { dimensions: 2, fields: [...ANCHORED, 'useLimits', 'limits', 'useMotor', 'motor'], structs: { limits: { type: 'JointAngleLimits2D', switch: 'useLimits' }, ...MOTOR } },
|
|
973
|
+
DistanceJoint2D: { dimensions: 2, fields: [...ANCHORED, 'autoConfigureDistance', 'distance', 'maxDistanceOnly'], autoAnchor: false },
|
|
974
|
+
SpringJoint2D: { dimensions: 2, fields: [...ANCHORED, 'autoConfigureDistance', 'distance', 'dampingRatio', 'frequency'], autoAnchor: false },
|
|
975
|
+
SliderJoint2D: { dimensions: 2, fields: [...ANCHORED, 'autoConfigureAngle', 'angle', 'useLimits', 'limits', 'useMotor', 'motor'], structs: { limits: { type: 'JointTranslationLimits2D', switch: 'useLimits' }, ...MOTOR } },
|
|
976
|
+
WheelJoint2D: { dimensions: 2, fields: [...ANCHORED, 'suspension', 'useMotor', 'motor'], structs: { suspension: { type: 'JointSuspension2D', switch: '' }, ...MOTOR } },
|
|
977
|
+
FrictionJoint2D: { dimensions: 2, fields: [...ANCHORED, 'maxForce', 'maxTorque'] },
|
|
978
|
+
RelativeJoint2D: { dimensions: 2, fields: [...JOINT, 'maxForce', 'maxTorque', 'correctionScale', 'autoConfigureOffset', 'linearOffset', 'angularOffset'] },
|
|
979
|
+
TargetJoint2D: { dimensions: 2, fields: [...JOINT, 'anchor', 'autoConfigureTarget', 'target', 'maxForce', 'dampingRatio', 'frequency'] },
|
|
980
|
+
};
|
|
981
|
+
// --- values ------------------------------------------------------------------------------------
|
|
982
|
+
/** A number as the shortest text Scenoco reads back the same, rounded as the exporter rounds. */
|
|
983
|
+
/** three's position as Unity's: z negated. */
|
|
984
|
+
const mirror = ([x, y, z]) => [x, y, z === 0 ? 0 : -z];
|
|
985
|
+
/**
|
|
986
|
+
* A knot's Rotation in Unity's space: facing along the curve, its up the world's made square to the
|
|
987
|
+
* curve and turned `roll` radians about it, as SceNoCo banks a knot.
|
|
988
|
+
*/
|
|
989
|
+
function knotRotation(out, tin, roll) {
|
|
990
|
+
const forward = new Vector3(...out);
|
|
991
|
+
if (forward.lengthSq() < 1e-12)
|
|
992
|
+
forward.set(-tin[0], -tin[1], -tin[2]);
|
|
993
|
+
if (forward.lengthSq() < 1e-12)
|
|
994
|
+
forward.set(0, 0, 1);
|
|
995
|
+
forward.normalize();
|
|
996
|
+
const up = new Vector3(0, 1, 0);
|
|
997
|
+
if (Math.abs(forward.dot(up)) > 0.999)
|
|
998
|
+
up.set(0, 0, 1);
|
|
999
|
+
// Unity's LookRotation: right = up × forward, in its left-handed space.
|
|
1000
|
+
const right = new Vector3().crossVectors(up, forward).normalize();
|
|
1001
|
+
up.crossVectors(forward, right);
|
|
1002
|
+
const look = new Quaternion().setFromRotationMatrix(new Matrix4().makeBasis(right, up, forward));
|
|
1003
|
+
// Mirrored, a turn about the curve changes hands: SceNoCo's roll is Unity's −roll about z.
|
|
1004
|
+
return look.multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), -roll));
|
|
1005
|
+
}
|
|
1006
|
+
/** A value the converter mirrored as a vector, back in three's space — for a writer that mirrors itself. */
|
|
1007
|
+
const flipBack = mirror;
|
|
1008
|
+
function num(n) {
|
|
1009
|
+
const r = Math.round(n * 1e6) / 1e6;
|
|
1010
|
+
return Object.is(r, -0) ? '0' : String(r);
|
|
1011
|
+
}
|
|
1012
|
+
const vec = (v) => v.map(num).join(' ');
|
|
1013
|
+
/** A list of numbers or references: space-separated, or comma-separated when an item has a space. */
|
|
1014
|
+
const list = (items) => items.join(items.some((i) => /\s/.test(i)) ? ', ' : ' ');
|
|
1015
|
+
/**
|
|
1016
|
+
* Unity's Euler angles for a quaternion, in degrees: Quaternion.Euler(x, y, z) turns about z, then x,
|
|
1017
|
+
* then y — a matrix Ry·Rx·Rz, three's order 'YXZ' read in Unity's own space.
|
|
1018
|
+
*/
|
|
1019
|
+
export function eulerAngles([x, y, z, w]) {
|
|
1020
|
+
const m11 = 1 - 2 * (y * y + z * z), m12 = 2 * (x * y - z * w), m13 = 2 * (x * z + y * w);
|
|
1021
|
+
const m21 = 2 * (x * y + z * w), m22 = 1 - 2 * (x * x + z * z), m23 = 2 * (y * z - x * w);
|
|
1022
|
+
const m31 = 2 * (x * z - y * w), m33 = 1 - 2 * (x * x + y * y);
|
|
1023
|
+
const ex = Math.asin(Math.max(-1, Math.min(1, -m23)));
|
|
1024
|
+
let ey, ez;
|
|
1025
|
+
if (Math.abs(m23) < 0.9999999) {
|
|
1026
|
+
ey = Math.atan2(m13, m33);
|
|
1027
|
+
ez = Math.atan2(m21, m22);
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
ey = Math.atan2(-m31, m11);
|
|
1031
|
+
ez = 0;
|
|
1032
|
+
}
|
|
1033
|
+
return [ex, ey, ez].map((a) => Math.round(((a * 180) / Math.PI) * 1e4) / 1e4 || 0);
|
|
1034
|
+
}
|
|
1035
|
+
// --- the text ----------------------------------------------------------------------------------
|
|
1036
|
+
class El {
|
|
1037
|
+
attrs = [];
|
|
1038
|
+
children = [];
|
|
1039
|
+
tag;
|
|
1040
|
+
constructor(tag) {
|
|
1041
|
+
this.tag = tag;
|
|
1042
|
+
}
|
|
1043
|
+
set(key, value) {
|
|
1044
|
+
const at = this.attrs.findIndex(([k]) => k === key);
|
|
1045
|
+
if (at >= 0)
|
|
1046
|
+
this.attrs[at] = [key, value];
|
|
1047
|
+
else
|
|
1048
|
+
this.attrs.push([key, value]);
|
|
1049
|
+
return this;
|
|
1050
|
+
}
|
|
1051
|
+
get(key) {
|
|
1052
|
+
return this.attrs.find(([k]) => k === key)?.[1];
|
|
1053
|
+
}
|
|
1054
|
+
add(...children) {
|
|
1055
|
+
this.children.push(...children);
|
|
1056
|
+
return this;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
/** An element and everything under it, anew: one written in two places. */
|
|
1060
|
+
function copy(e) {
|
|
1061
|
+
const out = new El(e.tag);
|
|
1062
|
+
out.attrs = e.attrs.map(([k, v]) => [k, v]);
|
|
1063
|
+
out.children = e.children.map(copy);
|
|
1064
|
+
return out;
|
|
1065
|
+
}
|
|
1066
|
+
const escape = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
|
1067
|
+
/** Scenoco's house style: two spaces a level, one element a line, empty elements closed in place. */
|
|
1068
|
+
function print(e, depth = 0) {
|
|
1069
|
+
const pad = ' '.repeat(depth);
|
|
1070
|
+
const attrs = e.attrs.map(([k, v]) => ` ${k}="${escape(v)}"`).join('');
|
|
1071
|
+
if (!e.children.length)
|
|
1072
|
+
return `${pad}<${e.tag}${attrs} />\n`;
|
|
1073
|
+
return `${pad}<${e.tag}${attrs}>\n${e.children.map((c) => print(c, depth + 1)).join('')}${pad}</${e.tag}>\n`;
|
|
1074
|
+
}
|