@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
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @scenoco-three/unity
|
|
2
2
|
|
|
3
|
-
A SceNoCo game
|
|
3
|
+
A SceNoCo game written into a Unity project as Unity's own assets, with its code as C# stubs to port.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
npx scenoco-unity path/to/UnityProject --root path/to/game
|
|
@@ -16,11 +16,27 @@ Unity builds them the next time it compiles (or from **SceNoCo ▸ Import**):
|
|
|
16
16
|
shape the web game draws. Two geometries with the same vertices are one mesh.
|
|
17
17
|
- **Materials** in `Assets/Materials/` (URP Lit or Unlit), shared exactly as three.js shares them: one
|
|
18
18
|
made in `assets.ts` is one asset for every renderer that uses it, so Unity batches them; one written
|
|
19
|
-
inside an element is that element's own, even if another looks the same.
|
|
19
|
+
inside an element is that element's own, even if another looks the same. A texture drawn on a canvas
|
|
20
|
+
is saved as a PNG.
|
|
21
|
+
- **Particle systems** as Unity's own, module by module: main, emission and bursts, shape, noise,
|
|
22
|
+
colour, size and rotation over lifetime.
|
|
23
|
+
- **Physics layers**, named after the game's constants, and the pairs it ignores in the project's
|
|
24
|
+
collision matrix.
|
|
25
|
+
- **The page** as UI Toolkit: one UXML per `UIDocument` and per `<template>`, its style as USS, with
|
|
26
|
+
panel settings at the same reference resolution, and Google Fonts fetched as TTF.
|
|
27
|
+
- **Input**: core's named axes and buttons as the project-wide input actions, and an EventSystem in
|
|
28
|
+
the first scene, kept across scenes.
|
|
29
|
+
- **Rendering settings** for a three.js game: Linear colour, HDR, Forward+, no MSAA.
|
|
20
30
|
- **Behaviours** as MonoBehaviours. A game behaviour gets a C# stub in `Assets/Scripts/` with the
|
|
21
|
-
fields its elements write, already set on every prefab and scene
|
|
22
|
-
|
|
23
|
-
|
|
31
|
+
fields its elements write, already set on every prefab and scene, and every other member with a C#
|
|
32
|
+
signature and its TypeScript inside as comments, to port in place. Every other module becomes
|
|
33
|
+
`Assets/Scripts/Modules/*.cs`, its TypeScript in comments. Stubs are written once and never
|
|
34
|
+
overwritten. Rapier's and Box2D's components become Unity's own rigidbodies and colliders,
|
|
35
|
+
and Box2D's joints Unity's 2D joints.
|
|
36
|
+
- **For the port**: `Assets/SceNoCo/PORTING.md`, the rules a port follows — code, data, UI — and the
|
|
37
|
+
`scenoco` commands for Unity's CLI, which drive the game in Play mode as `window.__scenoco` drives
|
|
38
|
+
it on the web: a held clock, input, readings (`unity command scenoco.help`; needs
|
|
39
|
+
`com.unity.pipeline`). `unity command scenoco.import` imports and returns the warnings.
|
|
24
40
|
|
|
25
41
|
The game is read in its own page, through its own Vite dev server and a headless Chrome: every
|
|
26
42
|
module but the entry is imported, so nothing starts, and each prefab is built with its behaviours
|
package/dist/cli.js
CHANGED
|
@@ -34,11 +34,18 @@ if (!project || args.length > 1 || unknown) {
|
|
|
34
34
|
}
|
|
35
35
|
try {
|
|
36
36
|
const snap = await snapshotProject(root, { headed });
|
|
37
|
-
const { converted, scripts } = writeUnity(snap, project, root);
|
|
37
|
+
const { converted, scripts, modules, warnings } = await writeUnity(snap, project, root);
|
|
38
38
|
const d = converted.data;
|
|
39
39
|
console.log(`${d.prefabs.length} prefabs, ${d.scenes.length} scenes, ${d.meshes.length} meshes, ${d.materials.length} materials → ${resolve(project)}`);
|
|
40
40
|
if (scripts.length)
|
|
41
|
-
console.log(`C# stubs for ${scripts.join(', ')} in Assets/Scripts — the fields are wired,
|
|
41
|
+
console.log(`C# stubs for ${scripts.join(', ')} in Assets/Scripts — the fields are wired, each method holds its TypeScript to port.`);
|
|
42
|
+
if (modules.length)
|
|
43
|
+
console.log(`The rest of the code, as TypeScript in Assets/Scripts/Modules: ${modules.map((m) => m.replace(/^\/src\//, '')).join(', ')}.`);
|
|
44
|
+
if (d.ui && Object.keys(d.ui.documents).length)
|
|
45
|
+
console.log(`The page as UXML and USS in Assets/UI: ${Object.values(d.ui.documents).join(', ')}.`);
|
|
46
|
+
for (const w of warnings)
|
|
47
|
+
console.log(`warning: ${w}`);
|
|
48
|
+
console.log('Porting rules: Assets/SceNoCo/PORTING.md. Driving the game in Play mode: unity command scenoco.help (needs com.unity.pipeline).');
|
|
42
49
|
for (const w of d.warnings)
|
|
43
50
|
console.log(`warning: ${w}`);
|
|
44
51
|
console.log('Unity builds them when it next compiles, or from SceNoCo ▸ Import.');
|
package/dist/convert.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A snapshot in Unity's terms: its handedness, its units, its asset paths, and C# for every game
|
|
3
|
-
* behaviour
|
|
3
|
+
* behaviour.
|
|
4
4
|
*
|
|
5
5
|
* three.js is right-handed and Unity left-handed, both Y up: mirroring Z maps one onto the other.
|
|
6
6
|
* A position or vector negates z, a rotation negates x and y of its quaternion, a mesh negates z of
|
|
@@ -32,11 +32,11 @@ export type UnityValue = null | number | boolean | string | {
|
|
|
32
32
|
} | {
|
|
33
33
|
asset: string;
|
|
34
34
|
}
|
|
35
|
-
/** A plain
|
|
35
|
+
/** A plain object — a physics material, a particle effect — which the importer reads as it is. */
|
|
36
36
|
| {
|
|
37
37
|
object: {
|
|
38
38
|
type: string;
|
|
39
|
-
fields: Record<string,
|
|
39
|
+
fields: Record<string, UnityValue>;
|
|
40
40
|
};
|
|
41
41
|
};
|
|
42
42
|
export interface UnityComponent {
|
|
@@ -81,6 +81,8 @@ export interface UnityNode {
|
|
|
81
81
|
components: UnityComponent[];
|
|
82
82
|
/** A nested prefab's asset path. */
|
|
83
83
|
prefab?: string;
|
|
84
|
+
/** Its Unity layer, from a collider's `layer`: SceNoCo's layer n is Unity's user layer n + 7. */
|
|
85
|
+
layer?: number;
|
|
84
86
|
children: UnityNode[];
|
|
85
87
|
source?: string;
|
|
86
88
|
}
|
|
@@ -108,6 +110,9 @@ export interface UnityMaterial {
|
|
|
108
110
|
emissionIntensity?: number;
|
|
109
111
|
/** The texture's asset path, once the exporter copied it in. */
|
|
110
112
|
texture?: string;
|
|
113
|
+
emissionTexture?: string;
|
|
114
|
+
/** How often the textures repeat: three's `texture.repeat`, Unity's tiling. */
|
|
115
|
+
tiling?: number[];
|
|
111
116
|
}
|
|
112
117
|
export interface UnityPrefab {
|
|
113
118
|
path: string;
|
|
@@ -142,8 +147,23 @@ export interface UnityExport {
|
|
|
142
147
|
prefabs: UnityPrefab[];
|
|
143
148
|
/** The first is the one to play first. */
|
|
144
149
|
scenes: UnityScene[];
|
|
150
|
+
/** User layers by Unity number — their names, and the pairs that pass through each other. */
|
|
151
|
+
layers: {
|
|
152
|
+
names: Record<number, string>;
|
|
153
|
+
ignore2D: [number, number][];
|
|
154
|
+
ignore3D: [number, number][];
|
|
155
|
+
};
|
|
156
|
+
/** The page's UXML by the element a UIDocument names, and the panels' theme. */
|
|
157
|
+
ui?: {
|
|
158
|
+
documents: Record<string, string>;
|
|
159
|
+
theme: string;
|
|
160
|
+
};
|
|
161
|
+
/** The project-wide input actions asset. */
|
|
162
|
+
input?: string;
|
|
145
163
|
warnings: string[];
|
|
146
164
|
}
|
|
165
|
+
/** SceNoCo's layers are 0 to 15, Unity's own 0 to 5: layer n, past 0, is Unity's user layer n + 7. */
|
|
166
|
+
export declare const unityLayer: (n: number) => number;
|
|
147
167
|
/** A texture's URL as the page loaded it, and where its file is in the project. */
|
|
148
168
|
export type TextureSource = (url: string) => {
|
|
149
169
|
file: string;
|
|
@@ -158,7 +178,17 @@ export interface Converted {
|
|
|
158
178
|
}
|
|
159
179
|
/** A game behaviour's C# class name. */
|
|
160
180
|
export declare const csName: (type: string) => string;
|
|
161
|
-
export
|
|
181
|
+
export interface ConvertOptions {
|
|
182
|
+
/** The scene `main.ts` plays: listed first in Build Settings. */
|
|
162
183
|
firstScene?: string;
|
|
163
184
|
textures?: TextureSource;
|
|
164
|
-
|
|
185
|
+
/** A behaviour's TypeScript, by the module path the snapshot gives (`/src/Player.ts`): its stub then carries every member. */
|
|
186
|
+
source?: (file: string) => string | null;
|
|
187
|
+
/** The game's layers as SceNoCo numbers them: names, and the pairs its physics ignores. */
|
|
188
|
+
layers?: {
|
|
189
|
+
names: Record<number, string>;
|
|
190
|
+
ignore2D: [number, number][];
|
|
191
|
+
ignore3D: [number, number][];
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
export declare function convert(snap: Snapshot, options?: ConvertOptions): Converted;
|
package/dist/convert.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { outsideClasses, readClass, stubClass } from './stub.js';
|
|
2
|
+
/** SceNoCo's layers are 0 to 15, Unity's own 0 to 5: layer n, past 0, is Unity's user layer n + 7. */
|
|
3
|
+
export const unityLayer = (n) => (n === 0 ? 0 : n + 7);
|
|
1
4
|
/**
|
|
2
5
|
* Names Unity already gives a component or a class every script sees. A game behaviour called one
|
|
3
6
|
* of them cannot be added to an object (Unity refuses a script named `Grid`), or shadows what a port
|
|
@@ -66,6 +69,8 @@ export function convert(snap, options = {}) {
|
|
|
66
69
|
return { asset: materialPath.get(v.material) };
|
|
67
70
|
if ('geometry' in v)
|
|
68
71
|
return { asset: meshPath.get(v.geometry) };
|
|
72
|
+
if ('object' in v)
|
|
73
|
+
return { object: { type: v.object.type, fields: Object.fromEntries(Object.entries(v.object.fields).map(([k, f]) => [k, value(f)])) } };
|
|
69
74
|
return v;
|
|
70
75
|
};
|
|
71
76
|
let ambient;
|
|
@@ -90,6 +95,10 @@ export function convert(snap, options = {}) {
|
|
|
90
95
|
};
|
|
91
96
|
if (n.source)
|
|
92
97
|
out.source = n.source;
|
|
98
|
+
// A collider's layer is its object's in Unity.
|
|
99
|
+
const layered = n.components.find((c) => !c.game && typeof c.fields.layer === 'number' && c.fields.layer > 0);
|
|
100
|
+
if (layered)
|
|
101
|
+
out.layer = unityLayer(layered.fields.layer);
|
|
93
102
|
if (!n.visible) {
|
|
94
103
|
// three hides the subtree and keeps its behaviours running; Unity's inactive object stops them.
|
|
95
104
|
if (hasComponents(n))
|
|
@@ -152,8 +161,11 @@ export function convert(snap, options = {}) {
|
|
|
152
161
|
}
|
|
153
162
|
ambient = undefined;
|
|
154
163
|
const root = node(p.root);
|
|
155
|
-
// The scene's own components, if any, need an object to live on
|
|
156
|
-
|
|
164
|
+
// The scene's own components, if any, need an object to live on: the first root, before the
|
|
165
|
+
// scene's children — so a reference into the scene, a path of child indices, moves one along.
|
|
166
|
+
const roots = root.components.length
|
|
167
|
+
? shiftNodes([{ ...root, name: p.name, position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], children: [] }, ...root.children])
|
|
168
|
+
: root.children;
|
|
157
169
|
const scene = { path: `Assets/Scenes/${sceneName.get(p.id)}.unity`, roots };
|
|
158
170
|
if (p.background)
|
|
159
171
|
scene.background = p.background;
|
|
@@ -168,7 +180,34 @@ export function convert(snap, options = {}) {
|
|
|
168
180
|
if (first > 0)
|
|
169
181
|
scenes.unshift(...scenes.splice(first, 1));
|
|
170
182
|
}
|
|
171
|
-
|
|
183
|
+
const given = options.layers ?? { names: {}, ignore2D: [], ignore3D: [] };
|
|
184
|
+
const used = new Set([...given.ignore2D.flat(), ...given.ignore3D.flat(), ...Object.keys(given.names).map(Number)].filter((n) => n > 0));
|
|
185
|
+
const layers = {
|
|
186
|
+
names: Object.fromEntries([...used].map((n) => [unityLayer(n), given.names[n] ?? `Layer ${n}`])),
|
|
187
|
+
ignore2D: given.ignore2D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
188
|
+
ignore3D: given.ignore3D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
189
|
+
};
|
|
190
|
+
return { data: { meshes, materials, prefabs, scenes, layers, warnings }, scripts: scripts(snap, value, options.source), copies };
|
|
191
|
+
}
|
|
192
|
+
/** Every node reference in `roots` one root further along; the scene itself (`''`) is now the first root. */
|
|
193
|
+
function shiftNodes(roots) {
|
|
194
|
+
const shift = (v) => {
|
|
195
|
+
if (!v || typeof v !== 'object')
|
|
196
|
+
return v;
|
|
197
|
+
if ('array' in v)
|
|
198
|
+
return { array: v.array.map(shift) };
|
|
199
|
+
if ('node' in v) {
|
|
200
|
+
const [first, ...rest] = v.node === '' ? ['-1'] : v.node.split('/');
|
|
201
|
+
return { ...v, node: [String(Number(first) + 1), ...rest].join('/') };
|
|
202
|
+
}
|
|
203
|
+
return v;
|
|
204
|
+
};
|
|
205
|
+
const visit = (n) => ({
|
|
206
|
+
...n,
|
|
207
|
+
components: n.components.map((c) => ({ ...c, fields: Object.fromEntries(Object.entries(c.fields).map(([k, v]) => [k, shift(v)])) })),
|
|
208
|
+
children: n.children.map(visit),
|
|
209
|
+
});
|
|
210
|
+
return roots.map(visit);
|
|
172
211
|
}
|
|
173
212
|
function hasComponents(n) {
|
|
174
213
|
return n.components.length > 0 || n.children.some(hasComponents);
|
|
@@ -230,15 +269,20 @@ function material(m, path, textures, copies, warnings) {
|
|
|
230
269
|
out.emission = m.emissive;
|
|
231
270
|
out.emissionIntensity = m.emissiveIntensity ?? 1;
|
|
232
271
|
}
|
|
233
|
-
|
|
234
|
-
const
|
|
272
|
+
for (const [slot, key] of [['map', 'texture'], ['emissiveMap', 'emissionTexture']]) {
|
|
273
|
+
const url = m[slot];
|
|
274
|
+
if (!url)
|
|
275
|
+
continue;
|
|
276
|
+
const found = textures?.(url);
|
|
235
277
|
if (found) {
|
|
236
|
-
out
|
|
237
|
-
copies.set(found.file, out
|
|
278
|
+
out[key] = `Assets/Textures/${found.name}`;
|
|
279
|
+
copies.set(found.file, out[key]);
|
|
238
280
|
}
|
|
239
281
|
else
|
|
240
|
-
warnings.push(`${m.source ?? m.name}:
|
|
282
|
+
warnings.push(`${m.source ?? m.name}: ${slot} ${url.startsWith('data:') ? '(drawn in code)' : url} was not found in the project — left off.`);
|
|
241
283
|
}
|
|
284
|
+
if (m.repeat)
|
|
285
|
+
out.tiling = m.repeat;
|
|
242
286
|
if (m.vertexColors)
|
|
243
287
|
warnings.push(`${m.source ?? m.name}: vertex colours are not exported.`);
|
|
244
288
|
if (m.flatShading)
|
|
@@ -321,11 +365,11 @@ function mix(a, b) {
|
|
|
321
365
|
}
|
|
322
366
|
// --- C# for game behaviours ----------------------------------------------------------------------
|
|
323
367
|
/**
|
|
324
|
-
* One MonoBehaviour per game behaviour
|
|
325
|
-
* written, started from the defaults a fresh instance holds
|
|
326
|
-
*
|
|
368
|
+
* One MonoBehaviour per game behaviour: the fields its elements write — typed from the values
|
|
369
|
+
* written, started from the defaults a fresh instance holds — and, from its TypeScript, every other
|
|
370
|
+
* member with that member's code inside it as comments, for a port to write in place.
|
|
327
371
|
*/
|
|
328
|
-
function scripts(snap, value) {
|
|
372
|
+
function scripts(snap, value, source) {
|
|
329
373
|
const seen = new Map();
|
|
330
374
|
const visit = (n) => {
|
|
331
375
|
for (const c of n.components) {
|
|
@@ -339,16 +383,29 @@ function scripts(snap, value) {
|
|
|
339
383
|
n.children.forEach(visit);
|
|
340
384
|
};
|
|
341
385
|
snap.prefabs.forEach((p) => visit(p.root));
|
|
386
|
+
const classes = new Map(Object.keys(snap.classes).map((type) => [type, csName(type)]));
|
|
342
387
|
const out = new Map();
|
|
343
|
-
|
|
388
|
+
// A file's code outside its behaviours goes with the first of them, once.
|
|
389
|
+
const outsideGiven = new Set();
|
|
390
|
+
for (const type of new Set([...seen.keys(), ...Object.keys(snap.classes)])) {
|
|
344
391
|
const info = snap.classes[type];
|
|
345
|
-
const
|
|
392
|
+
const wired = new Map();
|
|
393
|
+
for (const [name, values] of seen.get(type) ?? []) {
|
|
346
394
|
const cs = csType(values);
|
|
347
395
|
const fallback = info?.defaults[name];
|
|
348
396
|
const init = fallback === undefined ? '' : csValue(value(fallback), cs);
|
|
349
|
-
|
|
350
|
-
}
|
|
397
|
+
wired.set(name, cs ? ` public ${cs} ${name}${init ? ` = ${init}` : ''};` : ` // ${name}: always empty where it is written, so its type is unknown`);
|
|
398
|
+
}
|
|
351
399
|
const name = csName(type);
|
|
400
|
+
const code = info && source?.(info.file);
|
|
401
|
+
const cls = code ? readClass(code, info.file, type) : undefined;
|
|
402
|
+
if (cls) {
|
|
403
|
+
const file = info.file;
|
|
404
|
+
const outside = outsideGiven.has(file) ? [] : outsideClasses(code, file, Object.keys(snap.classes).filter((t) => snap.classes[t].file === file));
|
|
405
|
+
outsideGiven.add(file);
|
|
406
|
+
out.set(name, stubClass(name, file, cls, wired, classes, outside).replace(/^(public class)/m, `${name !== type ? `// Named ${name}: Unity has its own ${type}.\n` : ''}$1`));
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
352
409
|
out.set(name, [
|
|
353
410
|
'using UnityEngine;',
|
|
354
411
|
'',
|
|
@@ -357,7 +414,7 @@ function scripts(snap, value) {
|
|
|
357
414
|
...(name !== type ? [`// Named ${name}: Unity has its own ${type}.`] : []),
|
|
358
415
|
`public class ${name} : MonoBehaviour`,
|
|
359
416
|
'{',
|
|
360
|
-
...
|
|
417
|
+
...wired.values(),
|
|
361
418
|
'}',
|
|
362
419
|
'',
|
|
363
420
|
].join('\n'));
|
package/dist/export.d.ts
CHANGED
|
@@ -1,15 +1,44 @@
|
|
|
1
1
|
import type { Snapshot } from '@scenoco-three/core/snapshot';
|
|
2
2
|
import { type Converted } from './convert.js';
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Every module under `src/` the page may import: TypeScript and TSX, the game's entries left out, and
|
|
5
|
+
* so are `*.worker.ts` and `*.worklet.ts` — code for another thread, which no scene on the page holds.
|
|
6
|
+
*/
|
|
4
7
|
export declare function gameModules(root: string): string[];
|
|
5
8
|
/** Build the project's prefabs and scenes in its own page, and describe them. */
|
|
6
9
|
export declare function snapshotProject(root: string, options?: {
|
|
7
10
|
headed?: boolean;
|
|
8
|
-
}): Promise<
|
|
11
|
+
}): Promise<ExportSnapshot>;
|
|
9
12
|
export interface Written {
|
|
10
13
|
converted: Converted;
|
|
11
14
|
/** Stubs written; the rest already had a class of that name in the project. */
|
|
12
15
|
scripts: string[];
|
|
16
|
+
/** Module stubs written: the game's code outside its behaviours. */
|
|
17
|
+
modules: string[];
|
|
18
|
+
/** What the page, its fonts and its images could not carry across. */
|
|
19
|
+
warnings: string[];
|
|
13
20
|
}
|
|
14
|
-
/**
|
|
15
|
-
export
|
|
21
|
+
/** What the export page reads besides the snapshot: what the game's modules set up as they loaded. */
|
|
22
|
+
export interface ExportSnapshot extends Snapshot {
|
|
23
|
+
/** Core's named axes and buttons, `AXES`. */
|
|
24
|
+
axes?: Record<string, {
|
|
25
|
+
negative?: string[];
|
|
26
|
+
positive?: string[];
|
|
27
|
+
mouse?: number;
|
|
28
|
+
stick?: {
|
|
29
|
+
axis: number;
|
|
30
|
+
invert?: boolean;
|
|
31
|
+
};
|
|
32
|
+
}>;
|
|
33
|
+
/** Layer pairs that pass through each other, by physics package. */
|
|
34
|
+
ignore2D?: [number, number][];
|
|
35
|
+
ignore3D?: [number, number][];
|
|
36
|
+
/** A layer's name, from an exported constant such as `Layer = { ball: 1 }`. */
|
|
37
|
+
layerNames?: Record<number, string>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Convert a snapshot and write it into the Unity project: data for the importer, the importer, C# stubs,
|
|
41
|
+
* textures, the page as UXML and USS with its images and fonts, the input actions — and what the agent
|
|
42
|
+
* porting the game reads and drives it with: the porting rules, and the `scenoco` commands for Unity's CLI.
|
|
43
|
+
*/
|
|
44
|
+
export declare function writeUnity(snap: ExportSnapshot, project: string, root: string): Promise<Written>;
|
package/dist/export.js
CHANGED
|
@@ -5,15 +5,23 @@
|
|
|
5
5
|
* its entry — so nothing starts — and hands them to core's `snapshot`, in a headless Chrome: the
|
|
6
6
|
* declarations run where they were written to run, with the browser they may expect.
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
|
|
10
|
+
import { tmpdir } from 'node:os';
|
|
9
11
|
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
10
12
|
import { fileURLToPath } from 'node:url';
|
|
11
13
|
import { chromium } from 'playwright-core';
|
|
12
14
|
import { createServer, loadConfigFromFile } from 'vite';
|
|
13
15
|
import { convert } from './convert.js';
|
|
16
|
+
import { inputActions } from './input.js';
|
|
17
|
+
import { convertPage } from './page.js';
|
|
18
|
+
import { moduleStub } from './stub.js';
|
|
14
19
|
const PAGE = '/__scenoco_unity.html';
|
|
15
20
|
const ENTRY = 'virtual:scenoco-unity';
|
|
16
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Every module under `src/` the page may import: TypeScript and TSX, the game's entries left out, and
|
|
23
|
+
* so are `*.worker.ts` and `*.worklet.ts` — code for another thread, which no scene on the page holds.
|
|
24
|
+
*/
|
|
17
25
|
export function gameModules(root) {
|
|
18
26
|
const html = existsSync(join(root, 'index.html')) ? readFileSync(join(root, 'index.html'), 'utf8') : '';
|
|
19
27
|
const entries = new Set([...html.matchAll(/<script[^>]*type="module"[^>]*src="([^"]+)"/g)].map((m) => m[1].replace(/^\//, '')));
|
|
@@ -23,7 +31,7 @@ export function gameModules(root) {
|
|
|
23
31
|
const path = join(dir, name);
|
|
24
32
|
if (statSync(path).isDirectory())
|
|
25
33
|
walk(path);
|
|
26
|
-
else if (/\.tsx?$/.test(name) && !name.endsWith('.d.ts') && !/\.(test|spec)\.tsx?$/.test(name)) {
|
|
34
|
+
else if (/\.tsx?$/.test(name) && !name.endsWith('.d.ts') && !/\.(test|spec|worker|worklet)\.tsx?$/.test(name)) {
|
|
27
35
|
const rel = relative(root, path).split(sep).join('/');
|
|
28
36
|
if (!entries.has(rel))
|
|
29
37
|
out.push(`/${rel}`);
|
|
@@ -41,16 +49,36 @@ function html(root) {
|
|
|
41
49
|
const script = `<script type="module" src="/@id/${ENTRY}"></script>`;
|
|
42
50
|
return own.includes('</body>') ? own.replace('</body>', `${script}</body>`) : own + script;
|
|
43
51
|
}
|
|
52
|
+
/** The physics packages the game has, by the class whose layer matrix the export reads. */
|
|
53
|
+
const PHYSICS = [
|
|
54
|
+
['@scenoco-three/box2d', 'Physics2D', 'ignore2D'],
|
|
55
|
+
['@scenoco-three/rapier', 'Physics', 'ignore3D'],
|
|
56
|
+
];
|
|
44
57
|
function page(root, modules) {
|
|
58
|
+
// The game's own dependencies say which it has; in a workspace the package itself may be hoisted anywhere.
|
|
59
|
+
const json = existsSync(join(root, 'package.json')) ? JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) : {};
|
|
60
|
+
const deps = { ...json.dependencies, ...json.devDependencies };
|
|
61
|
+
const installed = PHYSICS.filter(([pkg]) => pkg in deps);
|
|
45
62
|
// Each import spelled out: Vite gives `import(variable)` a `?import` query, and with it a second
|
|
46
63
|
// copy of the module — whose prefabs would not be the ones the scenes hold.
|
|
47
64
|
const code = [
|
|
48
65
|
`import { snapshot } from '@scenoco-three/core/snapshot';`,
|
|
66
|
+
`import { AXES } from '@scenoco-three/core';`,
|
|
67
|
+
...installed.map(([pkg, name]) => `import { ${name} } from '${pkg}';`),
|
|
49
68
|
'window.__scenocoSnapshot = async () => {',
|
|
50
69
|
' const modules = {}, failed = [];',
|
|
51
70
|
...modules.map((file) => ` try { modules[${JSON.stringify(file)}] = await import(${JSON.stringify(file)}); } catch (e) { failed.push(${JSON.stringify(file)} + ': ' + e.message); }`),
|
|
52
71
|
' const out = snapshot(modules);',
|
|
53
72
|
" out.warnings.unshift(...failed.map((f) => f + ' — its prefabs are not exported.'));",
|
|
73
|
+
// What the modules set up as they loaded, which no element declares: the named axes, the layer matrix, the layers' names.
|
|
74
|
+
' out.axes = AXES;',
|
|
75
|
+
...installed.map(([, name, key]) => ` out.${key} = []; for (let a = 0; a < 16; a++) for (let b = a; b < 16; b++) if (${name}.getIgnoreLayerCollision(a, b)) out.${key}.push([a, b]);`),
|
|
76
|
+
' out.layerNames = {};',
|
|
77
|
+
' for (const mod of Object.values(modules)) for (const [name, value] of Object.entries(mod)) {',
|
|
78
|
+
' if (!/layer/i.test(name) || !value || typeof value !== "object") continue;',
|
|
79
|
+
' const entries = Object.entries(value);',
|
|
80
|
+
' if (entries.length && entries.every(([, n]) => Number.isInteger(n) && n > 0 && n < 16)) for (const [k, n] of entries) out.layerNames[n] = k;',
|
|
81
|
+
' }',
|
|
54
82
|
' return out;',
|
|
55
83
|
'};',
|
|
56
84
|
].join('\n');
|
|
@@ -136,8 +164,12 @@ function pageLoaded(tab) {
|
|
|
136
164
|
tab.waitForFunction(() => '__scenocoSnapshot' in window, null, { timeout: 30_000 }).then(() => finish('settled'), () => finish('settled'));
|
|
137
165
|
});
|
|
138
166
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
167
|
+
/**
|
|
168
|
+
* Convert a snapshot and write it into the Unity project: data for the importer, the importer, C# stubs,
|
|
169
|
+
* textures, the page as UXML and USS with its images and fonts, the input actions — and what the agent
|
|
170
|
+
* porting the game reads and drives it with: the porting rules, and the `scenoco` commands for Unity's CLI.
|
|
171
|
+
*/
|
|
172
|
+
export async function writeUnity(snap, project, root) {
|
|
141
173
|
project = resolve(project);
|
|
142
174
|
if (!existsSync(join(project, 'Assets')) || !existsSync(join(project, 'ProjectSettings'))) {
|
|
143
175
|
throw new Error(`${project} is not a Unity project: it has no Assets/ and ProjectSettings/.`);
|
|
@@ -149,27 +181,82 @@ export function writeUnity(snap, project, root) {
|
|
|
149
181
|
};
|
|
150
182
|
// Sources are absolute in the page; a person reads them from the project.
|
|
151
183
|
const tidy = (snapshot) => JSON.parse(JSON.stringify(snapshot), (key, value) => (key === 'source' && typeof value === 'string' ? relativeSource(value) : value));
|
|
184
|
+
// A texture drawn in code arrives as its canvas' PNG: written out, named by its content.
|
|
185
|
+
const drawn = mkdtempSync(join(tmpdir(), 'scenoco-unity-'));
|
|
152
186
|
const converted = convert(tidy(snap), {
|
|
153
187
|
firstScene: firstScene(root),
|
|
188
|
+
source: (file) => {
|
|
189
|
+
const path = join(root, file);
|
|
190
|
+
return existsSync(path) ? readFileSync(path, 'utf8') : null;
|
|
191
|
+
},
|
|
154
192
|
textures: (url) => {
|
|
193
|
+
if (url.startsWith('data:image/png;base64,')) {
|
|
194
|
+
const bytes = Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');
|
|
195
|
+
const name = `drawn-${createHash('sha1').update(bytes).digest('hex').slice(0, 10)}.png`;
|
|
196
|
+
writeFileSync(join(drawn, name), bytes);
|
|
197
|
+
return { file: join(drawn, name), name };
|
|
198
|
+
}
|
|
155
199
|
const path = decodeURIComponent(new URL(url, 'http://x').pathname);
|
|
156
200
|
for (const file of [join(root, 'public', path), join(root, path)])
|
|
157
201
|
if (existsSync(file) && statSync(file).isFile())
|
|
158
202
|
return { file, name: basename(file) };
|
|
159
203
|
return null;
|
|
160
204
|
},
|
|
205
|
+
layers: { names: snap.layerNames ?? {}, ignore2D: snap.ignore2D ?? [], ignore3D: snap.ignore3D ?? [] },
|
|
161
206
|
});
|
|
162
207
|
const out = (path) => {
|
|
163
208
|
const full = join(project, path);
|
|
164
209
|
mkdirSync(dirname(full), { recursive: true });
|
|
165
210
|
return full;
|
|
166
211
|
};
|
|
212
|
+
const warnings = [];
|
|
213
|
+
// The page: each UIDocument's element as UXML, the style as USS, with its images and web fonts.
|
|
214
|
+
const elements = new Set();
|
|
215
|
+
const visit = (n) => {
|
|
216
|
+
for (const c of n.components)
|
|
217
|
+
if (c.type === 'UIDocument')
|
|
218
|
+
elements.add(typeof c.fields.element === 'string' ? c.fields.element : 'ui');
|
|
219
|
+
n.children.forEach(visit);
|
|
220
|
+
};
|
|
221
|
+
snap.prefabs.forEach((p) => visit(p.root));
|
|
222
|
+
const page = await convertPage(root, [...elements]);
|
|
223
|
+
warnings.push(...page.warnings);
|
|
224
|
+
for (const [path, text] of page.files)
|
|
225
|
+
writeFileSync(out(path), text);
|
|
226
|
+
for (const [from, to] of page.copies)
|
|
227
|
+
copyFileSync(from, out(to));
|
|
228
|
+
for (const [url, to] of page.downloads) {
|
|
229
|
+
if (existsSync(join(project, to)))
|
|
230
|
+
continue;
|
|
231
|
+
try {
|
|
232
|
+
const response = await fetch(url);
|
|
233
|
+
if (!response.ok)
|
|
234
|
+
throw new Error(`HTTP ${response.status}`);
|
|
235
|
+
writeFileSync(out(to), Buffer.from(await response.arrayBuffer()));
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
warnings.push(`${url} could not be downloaded — ${error.message}.`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
converted.data.ui = { documents: Object.fromEntries(page.documents), theme: 'Assets/UI/Theme.tss' };
|
|
242
|
+
// SceNoCo's named axes and buttons as the project-wide input actions.
|
|
243
|
+
if (snap.axes) {
|
|
244
|
+
writeFileSync(out('Assets/SceNoCo/Input/SceNoCo.inputactions'), inputActions(snap.axes));
|
|
245
|
+
converted.data.input = 'Assets/SceNoCo/Input/SceNoCo.inputactions';
|
|
246
|
+
}
|
|
167
247
|
writeFileSync(out('Assets/SceNoCo/export.json'), JSON.stringify(converted.data));
|
|
168
248
|
// A dot file: Unity does not import it, the importer reads it as "a fresh export is waiting".
|
|
169
249
|
writeFileSync(out('Assets/SceNoCo/.pending'), new Date().toISOString());
|
|
170
|
-
|
|
250
|
+
const own = (file) => fileURLToPath(new URL(`../unity/${file}`, import.meta.url));
|
|
251
|
+
copyFileSync(own('SceNoCoImporter.cs'), out('Assets/Editor/SceNoCoImporter.cs'));
|
|
252
|
+
// Rewritten by every export, as the importer is: they are the exporter's, not the port's.
|
|
253
|
+
copyFileSync(own('PORTING.md'), out('Assets/SceNoCo/PORTING.md'));
|
|
254
|
+
copyFileSync(own('KeepAcrossScenes.cs'), out('Assets/SceNoCo/Runtime/KeepAcrossScenes.cs'));
|
|
255
|
+
for (const file of ['SceNoCoDriver.cs', 'SceNoCo.Driver.asmdef'])
|
|
256
|
+
copyFileSync(own(`Driver/${file}`), out(`Assets/SceNoCo/Driver/${file}`));
|
|
171
257
|
for (const [from, to] of converted.copies)
|
|
172
258
|
copyFileSync(from, out(to));
|
|
259
|
+
rmSync(drawn, { recursive: true, force: true });
|
|
173
260
|
const declared = classesIn(join(project, 'Assets'));
|
|
174
261
|
const scripts = [];
|
|
175
262
|
for (const [type, code] of converted.scripts) {
|
|
@@ -178,7 +265,35 @@ export function writeUnity(snap, project, root) {
|
|
|
178
265
|
writeFileSync(out(`Assets/Scripts/${type}.cs`), code);
|
|
179
266
|
scripts.push(type);
|
|
180
267
|
}
|
|
181
|
-
|
|
268
|
+
// The rest of the game's code — modules with no behaviour — as TypeScript in a .cs each, written once.
|
|
269
|
+
const behaviourFiles = new Set(Object.values(snap.classes).map((c) => c.file));
|
|
270
|
+
const modules = [];
|
|
271
|
+
for (const file of sourceFiles(root)) {
|
|
272
|
+
if (behaviourFiles.has(file))
|
|
273
|
+
continue;
|
|
274
|
+
const target = out(`Assets/Scripts/Modules/${file.replace(/^\/src\//, '').replace(/\.tsx?$/, '')}.cs`);
|
|
275
|
+
if (existsSync(target))
|
|
276
|
+
continue;
|
|
277
|
+
writeFileSync(target, moduleStub(file, readFileSync(join(root, file), 'utf8')));
|
|
278
|
+
modules.push(file);
|
|
279
|
+
}
|
|
280
|
+
return { converted, scripts, modules, warnings };
|
|
281
|
+
}
|
|
282
|
+
/** Every TypeScript module under `src/` — the entry too — but the scenes, which the export already carries. */
|
|
283
|
+
function sourceFiles(root) {
|
|
284
|
+
const out = [];
|
|
285
|
+
const walk = (dir) => {
|
|
286
|
+
for (const name of readdirSync(dir)) {
|
|
287
|
+
const path = join(dir, name);
|
|
288
|
+
if (statSync(path).isDirectory())
|
|
289
|
+
walk(path);
|
|
290
|
+
else if (/\.ts$/.test(name) && !/\.(d|test|spec)\.ts$/.test(name))
|
|
291
|
+
out.push(`/${relative(root, path).split(sep).join('/')}`);
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
if (existsSync(join(root, 'src')))
|
|
295
|
+
walk(join(root, 'src'));
|
|
296
|
+
return out.sort();
|
|
182
297
|
}
|
|
183
298
|
/** The scene `main.ts` plays: `play(Main)` names it. */
|
|
184
299
|
function firstScene(root) {
|
package/dist/input.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface Axis {
|
|
2
|
+
negative?: readonly string[];
|
|
3
|
+
positive?: readonly string[];
|
|
4
|
+
mouse?: number;
|
|
5
|
+
stick?: {
|
|
6
|
+
axis: number;
|
|
7
|
+
invert?: boolean;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/** A DOM key code — `KeyA`, `ArrowLeft`, `JoystickButton0` — as an Input System control path. */
|
|
11
|
+
export declare function controlPath(code: string): string | undefined;
|
|
12
|
+
/** The `.inputactions` JSON for `axes` — core's `AXES`, as the snapshot carries it. */
|
|
13
|
+
export declare function inputActions(axes: Record<string, Axis>): string;
|
|
14
|
+
export {};
|