@scenoco-three/unity 1.4.0 → 1.6.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/export.js CHANGED
@@ -15,7 +15,8 @@ import { createServer, loadConfigFromFile } from 'vite';
15
15
  import { convert } from './convert.js';
16
16
  import { inputActions } from './input.js';
17
17
  import { convertPage } from './page.js';
18
- import { moduleStub } from './stub.js';
18
+ import { moduleStub, typeAliases } from './stub.js';
19
+ import { twins } from './twin.js';
19
20
  const PAGE = '/__scenoco_unity.html';
20
21
  const ENTRY = 'virtual:scenoco-unity';
21
22
  /**
@@ -63,13 +64,21 @@ function page(root, modules) {
63
64
  // copy of the module — whose prefabs would not be the ones the scenes hold.
64
65
  const code = [
65
66
  `import { snapshot } from '@scenoco-three/core/snapshot';`,
66
- `import { AXES } from '@scenoco-three/core';`,
67
+ `import { AXES, Asset, loadAssets } from '@scenoco-three/core';`,
67
68
  ...installed.map(([pkg, name]) => `import { ${name} } from '${pkg}';`),
68
69
  'window.__scenocoSnapshot = async () => {',
69
70
  ' const modules = {}, failed = [];',
70
71
  ...modules.map((file) => ` try { modules[${JSON.stringify(file)}] = await import(${JSON.stringify(file)}); } catch (e) { failed.push(${JSON.stringify(file)} + ': ' + e.message); }`),
72
+ // What `main.ts` awaits before it plays — models, terrains — loaded as it would be: every asset the
73
+ // modules export, alone or in an object or a list, and every model prefab, so a scene that reads or places one finds it.
74
+ ' const assets = new Set(), seen = new Set();',
75
+ ' const find = (v, depth) => { if (typeof v === "function") { assets.add(v); return; } if (!v || typeof v !== "object" || seen.has(v) || depth > 3) return; seen.add(v); if (v instanceof Asset) { assets.add(v); return; } if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype) for (const x of Object.values(v)) find(x, depth + 1); };',
76
+ ' for (const mod of Object.values(modules)) for (const v of Object.values(mod)) find(v, 0);',
77
+ ' await Promise.all([...assets].map((a) => loadAssets(a).catch((e) => failed.push(`${a.url ?? a.constructor.name}: did not load — ${e.message}`))));',
71
78
  ' const out = snapshot(modules);',
72
- " out.warnings.unshift(...failed.map((f) => f + ' — its prefabs are not exported.'));",
79
+ // Every file the modules load — a sound kept in a table, not only one a field names — for the port to have.
80
+ ' out.files = [...assets].filter((a) => typeof a.url === "string").map((a) => ({ url: a.url, type: a.constructor.name }));',
81
+ " out.warnings.unshift(...failed.map((f) => (f.includes('did not load') ? f : f + ' — its prefabs are not exported.')));",
73
82
  // What the modules set up as they loaded, which no element declares: the named axes, the layer matrix, the layers' names.
74
83
  ' out.axes = AXES;',
75
84
  ...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]);`),
@@ -165,9 +174,10 @@ function pageLoaded(tab) {
165
174
  });
166
175
  }
167
176
  /**
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.
177
+ * Convert a snapshot and write it into the Unity project: the scenes and prefabs as Scenoco's text, data
178
+ * for the importer that makes the assets they name, the importer, C# stubs, textures, the page as UXML
179
+ * and USS with its images and fonts, the input actions — and the porting rules, with Scenoco and Diceload
180
+ * in the project's manifest for the agent that ports and checks it.
171
181
  */
172
182
  export async function writeUnity(snap, project, root) {
173
183
  project = resolve(project);
@@ -181,10 +191,25 @@ export async function writeUnity(snap, project, root) {
181
191
  };
182
192
  // Sources are absolute in the page; a person reads them from the project.
183
193
  const tidy = (snapshot) => JSON.parse(JSON.stringify(snapshot), (key, value) => (key === 'source' && typeof value === 'string' ? relativeSource(value) : value));
194
+ // The page: each UIDocument's element as UXML, the style as USS, with its images and web fonts.
195
+ const elements = new Set();
196
+ const visit = (n) => {
197
+ for (const c of n.components)
198
+ if (c.type === 'UIDocument')
199
+ elements.add(typeof c.fields.element === 'string' ? c.fields.element : 'ui');
200
+ n.children.forEach(visit);
201
+ };
202
+ snap.prefabs.forEach((p) => visit(p.root));
203
+ const page = await convertPage(root, [...elements]);
204
+ // Each <template> as UXML, by id: a behaviour that clones one gets a field for it.
205
+ const templates = Object.fromEntries(page.templates);
184
206
  // A texture drawn in code arrives as its canvas' PNG: written out, named by its content.
185
207
  const drawn = mkdtempSync(join(tmpdir(), 'scenoco-unity-'));
186
208
  const converted = convert(tidy(snap), {
187
209
  firstScene: firstScene(root),
210
+ aliases: aliasesIn(root),
211
+ templates,
212
+ files: snap.files?.filter((f) => f.type === 'Model' || f.type === 'AudioClip'),
188
213
  source: (file) => {
189
214
  const path = join(root, file);
190
215
  return existsSync(path) ? readFileSync(path, 'utf8') : null;
@@ -210,16 +235,6 @@ export async function writeUnity(snap, project, root) {
210
235
  return full;
211
236
  };
212
237
  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
238
  warnings.push(...page.warnings);
224
239
  for (const [path, text] of page.files)
225
240
  writeFileSync(out(path), text);
@@ -238,33 +253,91 @@ export async function writeUnity(snap, project, root) {
238
253
  warnings.push(`${url} could not be downloaded — ${error.message}.`);
239
254
  }
240
255
  }
241
- converted.data.ui = { documents: Object.fromEntries(page.documents), theme: 'Assets/UI/Theme.tss' };
256
+ const ui = { documents: Object.fromEntries(page.documents), theme: 'Assets/UI/Theme.tss' };
257
+ converted.data.ui = ui;
258
+ // Unity's own packages for what the game has: glTF models, splines.
259
+ const has = (type) => [...converted.data.prefabs.map((p) => p.root), ...converted.data.scenes.flatMap((sc) => sc.roots)].some(function visit(n) {
260
+ return n.components.some((c) => c.type === type) || n.children.some(visit);
261
+ });
262
+ const needed = {};
263
+ const models = [...converted.copies].filter(([, to]) => /\.(glb|gltf)$/i.test(to)).map(([from]) => from);
264
+ if (models.length)
265
+ needed['com.unity.cloud.gltfast'] = UNITY_PACKAGES['com.unity.cloud.gltfast'];
266
+ for (const name of gltfDecoders(models))
267
+ needed[name] = UNITY_PACKAGES[name];
268
+ if (has('SplineContainer'))
269
+ needed['com.unity.splines'] = UNITY_PACKAGES['com.unity.splines'];
270
+ const packages = addPackages(project, needed);
242
271
  // SceNoCo's named axes and buttons as the project-wide input actions.
243
272
  if (snap.axes) {
244
273
  writeFileSync(out('Assets/SceNoCo/Input/SceNoCo.inputactions'), inputActions(snap.axes));
245
274
  converted.data.input = 'Assets/SceNoCo/Input/SceNoCo.inputactions';
246
275
  }
247
- writeFileSync(out('Assets/SceNoCo/export.json'), JSON.stringify(converted.data));
276
+ // C# stubs, written once: a class the project has already is the port's, and its fields are what the scenes wire.
277
+ const declared = classesIn(join(project, 'Assets'));
278
+ const scripts = [];
279
+ for (const [type, code] of converted.scripts) {
280
+ if (declared.has(type))
281
+ continue;
282
+ writeFileSync(out(`Assets/Scripts/${type}.cs`), code);
283
+ declared.set(type, code);
284
+ scripts.push(type);
285
+ }
286
+ // The scenes and prefabs as text, left where Unity imports nothing until the importer has made what they name.
287
+ const manifest = readManifest(project);
288
+ const text = twins(converted.data, {
289
+ documents: ui.documents,
290
+ declares: (type, field) => serializedFields(declared.get(type) ?? '').has(field),
291
+ eventSystem: 'com.unity.ugui' in manifest && 'com.unity.inputsystem' in manifest,
292
+ });
293
+ if (!('com.unity.ugui' in manifest))
294
+ warnings.push("the project has no com.unity.ugui: the UI's EventSystem is left out of the first scene.");
295
+ warnings.push(...text.warnings);
296
+ rmSync(join(project, STAGED), { recursive: true, force: true });
297
+ for (const [path, body] of text.files)
298
+ writeFileSync(out(`${STAGED}/${path.slice('Assets/'.length)}`), body);
299
+ const t = converted.data;
300
+ // What only a placed copy named, where the prefab's own stands in, is made nowhere.
301
+ const named = [...text.files.values()].join('\n');
302
+ const data = {
303
+ meshes: t.meshes.filter((m) => named.includes(m.path)),
304
+ terrains: t.terrains,
305
+ materials: t.materials.filter((m) => named.includes(m.path)),
306
+ layers: t.layers,
307
+ modelVariants: t.modelVariants,
308
+ dataTextures: t.dataTextures,
309
+ input: t.input,
310
+ theme: ui.theme,
311
+ ...text.assets,
312
+ twins: [...text.files.keys()],
313
+ scenes: t.scenes.map(({ path, fog, ambient }) => ({ path, fog, ambient })),
314
+ warnings: [...new Set(t.warnings)],
315
+ };
316
+ writeFileSync(out('Assets/SceNoCo/export.json'), JSON.stringify(data));
248
317
  // A dot file: Unity does not import it, the importer reads it as "a fresh export is waiting".
249
318
  writeFileSync(out('Assets/SceNoCo/.pending'), new Date().toISOString());
250
319
  const own = (file) => fileURLToPath(new URL(`../unity/${file}`, import.meta.url));
251
320
  copyFileSync(own('SceNoCoImporter.cs'), out('Assets/Editor/SceNoCoImporter.cs'));
321
+ // SceNoCo's onValidate runs on a move too: in Unity, this script calls OnValidate for one.
322
+ copyFileSync(own('SceNoCoValidate.cs'), out('Assets/Editor/SceNoCoValidate.cs'));
252
323
  // Rewritten by every export, as the importer is: they are the exporter's, not the port's.
253
324
  copyFileSync(own('PORTING.md'), out('Assets/SceNoCo/PORTING.md'));
254
325
  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}`));
326
+ // Only for a game that uses them: they need the Splines package, which only such a game gets.
327
+ for (const [tag, file] of [['SplineKnotNodes', 'SplineKnotNodes.cs'], ['SplineMesh', 'SplineMesh.cs']]) {
328
+ const path = `Assets/SceNoCo/Runtime/${file}`;
329
+ if ([...text.files.values()].some((t) => t.includes(`<${tag} `) || t.includes(`<${tag}>`) || t.includes(`<${tag}/`)))
330
+ copyFileSync(own(file), out(path));
331
+ else
332
+ for (const old of [path, `${path}.meta`])
333
+ rmSync(join(project, old), { force: true });
334
+ }
335
+ // An earlier export's Play-mode commands: Diceload's simulations check the port now.
336
+ for (const old of ['Assets/SceNoCo/Driver', 'Assets/SceNoCo/Driver.meta'])
337
+ rmSync(join(project, old), { recursive: true, force: true });
257
338
  for (const [from, to] of converted.copies)
258
339
  copyFileSync(from, out(to));
259
340
  rmSync(drawn, { recursive: true, force: true });
260
- const declared = classesIn(join(project, 'Assets'));
261
- const scripts = [];
262
- for (const [type, code] of converted.scripts) {
263
- if (declared.has(type))
264
- continue;
265
- writeFileSync(out(`Assets/Scripts/${type}.cs`), code);
266
- scripts.push(type);
267
- }
268
341
  // The rest of the game's code — modules with no behaviour — as TypeScript in a .cs each, written once.
269
342
  const behaviourFiles = new Set(Object.values(snap.classes).map((c) => c.file));
270
343
  const modules = [];
@@ -277,7 +350,28 @@ export async function writeUnity(snap, project, root) {
277
350
  writeFileSync(target, moduleStub(file, readFileSync(join(root, file), 'utf8')));
278
351
  modules.push(file);
279
352
  }
280
- return { converted, scripts, modules, warnings };
353
+ // Tweens port to DOTween, which the export can't install: it needs the person (an Asset Store login, or a download).
354
+ const tweening = sourceFiles(root).filter((file) => usesTweens(readFileSync(join(root, file), 'utf8')));
355
+ if (tweening.length && !hasDotween(join(project, 'Assets'))) {
356
+ warnings.push(`the game tweens (${tweening.map((f) => f.replace(/^\/src\//, '')).join(', ')}): its port needs the free DOTween — Assets/SceNoCo/PORTING.md ▸ "Tweens" says how to install it.`);
357
+ }
358
+ // One line per thing said: a prefab placed fifty times says what its copies share once.
359
+ return { converted, twins: [...text.files.keys()], packages, scripts, modules, warnings: [...new Set(warnings)] };
360
+ }
361
+ /** Whether a module tweens with core's API — `Tween.sequence()`, `node.doMove(…)` — which a port writes with DOTween. */
362
+ export function usesTweens(code) {
363
+ return /\bTween\.(sequence|to|float|delayedCall|kill|killAll)\s*\(|\.do[A-Z]\w*\s*\(/.test(code);
364
+ }
365
+ /** Whether the Unity project has DOTween: its assembly anywhere under Assets. */
366
+ function hasDotween(dir) {
367
+ for (const name of readdirSync(dir)) {
368
+ const path = join(dir, name);
369
+ if (name === 'DOTween.dll')
370
+ return true;
371
+ if (statSync(path).isDirectory() && !name.endsWith('~') && hasDotween(path))
372
+ return true;
373
+ }
374
+ return false;
281
375
  }
282
376
  /** Every TypeScript module under `src/` — the entry too — but the scenes, which the export already carries. */
283
377
  function sourceFiles(root) {
@@ -295,23 +389,139 @@ function sourceFiles(root) {
295
389
  walk(join(root, 'src'));
296
390
  return out.sort();
297
391
  }
392
+ /** Every type alias the game's modules declare, by name; a name declared twice keeps its first. */
393
+ function aliasesIn(root) {
394
+ const out = new Map();
395
+ const walk = (dir) => {
396
+ for (const name of readdirSync(dir)) {
397
+ const path = join(dir, name);
398
+ if (statSync(path).isDirectory())
399
+ walk(path);
400
+ else if (/\.tsx?$/.test(name) && !name.endsWith('.d.ts')) {
401
+ try {
402
+ for (const [k, v] of typeAliases(readFileSync(path, 'utf8'), path))
403
+ if (!out.has(k))
404
+ out.set(k, v);
405
+ }
406
+ catch {
407
+ // A module that does not parse has no aliases to give; its own stub says what failed.
408
+ }
409
+ }
410
+ }
411
+ };
412
+ if (existsSync(join(root, 'src')))
413
+ walk(join(root, 'src'));
414
+ return out;
415
+ }
298
416
  /** The scene `main.ts` plays: `play(Main)` names it. */
299
417
  function firstScene(root) {
300
418
  const main = join(root, 'src', 'main.ts');
301
419
  return existsSync(main) ? /\bplay\(\s*(\w+)/.exec(readFileSync(main, 'utf8'))?.[1] : undefined;
302
420
  }
421
+ /** Every class the project's C# declares, with the text of its file. */
303
422
  function classesIn(dir) {
304
- const out = new Set();
423
+ const out = new Map();
305
424
  const walk = (d) => {
306
425
  for (const name of readdirSync(d)) {
307
426
  const path = join(d, name);
308
427
  if (statSync(path).isDirectory())
309
428
  walk(path);
310
- else if (name.endsWith('.cs'))
311
- for (const m of readFileSync(path, 'utf8').matchAll(/\bclass\s+(\w+)/g))
312
- out.add(m[1]);
429
+ else if (name.endsWith('.cs')) {
430
+ const code = readFileSync(path, 'utf8');
431
+ for (const m of code.matchAll(/\bclass\s+(\w+)/g))
432
+ out.set(m[1], code);
433
+ }
313
434
  }
314
435
  };
315
436
  walk(dir);
316
437
  return out;
317
438
  }
439
+ /**
440
+ * The fields a C# file declares that Unity serializes, as a scene sets them: public ones, and
441
+ * `[SerializeField]` ones — not static, const or readonly, not a property or a method.
442
+ */
443
+ export function serializedFields(code) {
444
+ const out = new Set();
445
+ for (const raw of code.split('\n')) {
446
+ const line = raw.replace(/\/\/.*$/, '');
447
+ if (!/\bpublic\b|\[SerializeField\]/.test(line) || /\b(static|const|readonly|class|struct|enum|interface|event)\b/.test(line))
448
+ continue;
449
+ if (line.includes('=>'))
450
+ continue;
451
+ // Brackets' insides first — `new(30, 30)`, `Dictionary<string, int>`, `[SerializeField]` — so a comma
452
+ // left is one between names: `public GameObject a, b = x, c;` declares three.
453
+ let flat = line;
454
+ for (let before = ''; before !== flat;) {
455
+ before = flat;
456
+ flat = flat.replace(/\([^()]*\)|\{[^{}]*\}|<[^<>]*>|\[[^[\]]*\]/g, '');
457
+ }
458
+ const m = /^\s*(?:(?:public|private|protected|internal|new)\s+)*[\w.?]+\s+([^;]+);\s*$/.exec(flat);
459
+ if (!m)
460
+ continue;
461
+ for (const part of m[1].split(',')) {
462
+ const name = /^\s*(\w+)\s*(=|$)/.exec(part)?.[1];
463
+ if (name)
464
+ out.add(name);
465
+ }
466
+ }
467
+ return out;
468
+ }
469
+ /** Where the export leaves the scenes' and prefabs' text for the importer: Unity imports nothing in a folder ending in ~. */
470
+ const STAGED = 'Assets/SceNoCo/Twins~';
471
+ /** The packages the export needs in the Unity project, at the versions it was written for. */
472
+ const PACKAGES = {
473
+ 'com.roro.scenoco': 'https://github.com/RomaRogov/scenoco-unity.git#v0.2.0',
474
+ 'com.roro.diceload': 'https://github.com/RomaRogov/diceload.git#v0.5.0',
475
+ };
476
+ /** Unity's packages the export adds when the game needs them, at versions Unity 6 takes. */
477
+ const UNITY_PACKAGES = {
478
+ 'com.unity.cloud.gltfast': '6.21.0',
479
+ // glTFast decodes a compressed model only with these beside it; meshopt's are all experimental releases.
480
+ 'com.unity.meshopt.decompress': '0.3.0-exp.1',
481
+ 'com.unity.cloud.draco': '5.6.0',
482
+ 'com.unity.cloud.ktx': '3.8.0',
483
+ 'com.unity.splines': '2.9.2',
484
+ };
485
+ /** The glTF extensions a model may need a decoder package for, by the package glTFast reads it with. */
486
+ const GLTF_DECODERS = {
487
+ EXT_meshopt_compression: 'com.unity.meshopt.decompress',
488
+ KHR_draco_mesh_compression: 'com.unity.cloud.draco',
489
+ KHR_texture_basisu: 'com.unity.cloud.ktx',
490
+ };
491
+ /** The decoder packages `files` (.glb or .gltf) need: read from each file's JSON, its `extensionsUsed`. */
492
+ export function gltfDecoders(files) {
493
+ const out = new Set();
494
+ for (const file of files) {
495
+ try {
496
+ const bytes = readFileSync(file);
497
+ // A .glb is a 12-byte header, then its JSON chunk: length, type, text.
498
+ const json = bytes.readUInt32LE(0) === 0x46546c67 ? bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString('utf8') : bytes.toString('utf8');
499
+ for (const ext of (JSON.parse(json).extensionsUsed ?? []))
500
+ if (GLTF_DECODERS[ext])
501
+ out.add(GLTF_DECODERS[ext]);
502
+ }
503
+ catch {
504
+ // A model that can't be read is glTFast's to report, at its import.
505
+ }
506
+ }
507
+ return out;
508
+ }
509
+ function readManifest(project) {
510
+ const file = join(project, 'Packages', 'manifest.json');
511
+ return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')).dependencies ?? {}) : {};
512
+ }
513
+ /** Scenoco and Diceload in the project's manifest, where it names neither: what was added. A version or path it gives is kept. */
514
+ function addPackages(project, extra = {}) {
515
+ const file = join(project, 'Packages', 'manifest.json');
516
+ if (!existsSync(file))
517
+ throw new Error(`${project} has no Packages/manifest.json.`);
518
+ const manifest = JSON.parse(readFileSync(file, 'utf8'));
519
+ manifest.dependencies ??= {};
520
+ const wanted = { ...PACKAGES, ...extra };
521
+ const added = Object.keys(wanted).filter((name) => !(name in manifest.dependencies));
522
+ for (const name of added)
523
+ manifest.dependencies[name] = wanted[name];
524
+ if (added.length)
525
+ writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`);
526
+ return added;
527
+ }
package/dist/page.d.ts CHANGED
@@ -14,6 +14,8 @@ export interface PageOutput {
14
14
  downloads: Map<string, string>;
15
15
  /** Each document's UXML, by the element it names. */
16
16
  documents: Map<string, string>;
17
+ /** Each `<template>`'s UXML, by its id. */
18
+ templates: Map<string, string>;
17
19
  warnings: string[];
18
20
  }
19
21
  /**
package/dist/page.js CHANGED
@@ -146,7 +146,7 @@ async function webFonts(html, warnings) {
146
146
  * its templates, and its style.
147
147
  */
148
148
  export async function convertPage(root, documents, options = {}) {
149
- const out = { files: new Map(), copies: new Map(), downloads: new Map(), documents: new Map(), warnings: [] };
149
+ const out = { files: new Map(), copies: new Map(), downloads: new Map(), documents: new Map(), templates: new Map(), warnings: [] };
150
150
  const file = join(root, 'index.html');
151
151
  if (!existsSync(file) || documents.length === 0)
152
152
  return out;
@@ -168,9 +168,14 @@ export async function convertPage(root, documents, options = {}) {
168
168
  out.downloads.set(url, path);
169
169
  // Picking. Core's UIDocument takes pointer events off its element, and the page gives them back
170
170
  // where a player taps: pointer-events is inherited, and the last rule that sets it on an element
171
- // wins. A rule that gives them back counts whatever classes it names — code puts `.shown` on as the
172
- // game runs, and USS has no picking to switch — while UI Toolkit picks nothing hidden anyway.
173
- const loose = (sel) => sel.replace(/\.[\w-]+|::?[\w-]+(\([^)]*\))?/g, '') || '*';
171
+ // wins. A rule that gives them back counts the classes code adds as the game runs — `.shown`, which no
172
+ // element of the page carries yet, and USS has no picking to switch — while UI Toolkit picks nothing
173
+ // hidden anyway. A class the page does carry (`.btn`) still has to match: `.btn` is not every element.
174
+ const carried = new Set(all(tree).flatMap((e) => (e.attrs.class ?? '').split(/\s+/).filter(Boolean)));
175
+ const loose = (sel) => {
176
+ const kept = sel.replace(/\.([\w-]+)/g, (whole, name) => (carried.has(name) ? whole : '')).replace(/::?[\w-]+(\([^)]*\))?/g, '').trim();
177
+ return kept || null;
178
+ };
174
179
  const picking = new Map();
175
180
  const pickable = (e) => {
176
181
  if (picking.has(e))
@@ -180,12 +185,14 @@ export async function convertPage(root, documents, options = {}) {
180
185
  for (const [p, v] of r.declarations) {
181
186
  if (p !== 'pointer-events')
182
187
  continue;
183
- if (v === 'none' ? r.selectors.some((sel) => !sel.includes(':') && matches(sel, e)) : r.selectors.some((sel) => matches(loose(sel), e)))
188
+ if (v === 'none' ? r.selectors.some((sel) => !sel.includes(':') && matches(sel, e)) : r.selectors.some((sel) => { const l = loose(sel); return l !== null && matches(l, e); }))
184
189
  value = v !== 'none';
185
190
  }
186
- // A document's element starts without them, and so does a template's, which code adds under one.
187
- const top = roots.includes(e) || e.parent?.tag === 'template';
188
- const result = value ?? (top || !e.parent || !inside.has(e.parent) ? !top : pickable(e.parent));
191
+ // A document's element starts without them. A template's inherits from no element of the page — code
192
+ // adds it under one — so it starts without them too, unless it is a button: a level's card.
193
+ const ofTemplate = e.parent?.tag === 'template';
194
+ const top = roots.includes(e) || ofTemplate;
195
+ const result = value ?? (ofTemplate ? e.tag === 'button' : top || !e.parent || !inside.has(e.parent) ? !top : pickable(e.parent));
189
196
  picking.set(e, result);
190
197
  return result;
191
198
  };
@@ -246,6 +253,12 @@ export async function convertPage(root, documents, options = {}) {
246
253
  case 'text-align':
247
254
  result.push(['-unity-text-align', { center: 'middle-center', left: 'middle-left', right: 'middle-right' }[value] ?? 'middle-left']);
248
255
  break;
256
+ case 'background-size':
257
+ result.push([prop, value]);
258
+ // A sized image tiles in CSS, which repeats by default; USS draws it once unless told.
259
+ if (!own.has('background-repeat') && !/^(cover|contain|100% 100%|auto)$/.test(value))
260
+ result.push(['background-repeat', 'repeat']);
261
+ break;
249
262
  case 'border': {
250
263
  const [width, , color] = value.split(/\s+(?![^(]*\))/);
251
264
  result.push(['border-width', width]);
@@ -317,8 +330,11 @@ export async function convertPage(root, documents, options = {}) {
317
330
  const attrs = [];
318
331
  if (e.attrs.id)
319
332
  attrs.push(`name="${escape(e.attrs.id)}"`);
320
- if (e.attrs.class)
321
- attrs.push(`class="${escape(e.attrs.class)}"`);
333
+ // A `data-button` — core's Input names its clicks — is a class, so a port finds every button of a
334
+ // name, id or none: `root.Query(className: "button-Pause")`.
335
+ const classes = [e.attrs.class, e.attrs['data-button'] ? `button-${e.attrs['data-button']}` : undefined].filter(Boolean).join(' ');
336
+ if (classes)
337
+ attrs.push(`class="${escape(classes)}"`);
322
338
  if (e.text)
323
339
  attrs.push(`text="${escape(e.text)}"`);
324
340
  if (e.attrs.style)
@@ -342,8 +358,10 @@ export async function convertPage(root, documents, options = {}) {
342
358
  const content = t.children.filter((c) => c.tag !== 'script');
343
359
  if (content.length !== 1)
344
360
  out.warnings.push(`index.html: <template id="${t.attrs.id}"> holds ${content.length} elements — a template's UXML holds its first.`);
345
- if (content[0])
346
- out.files.set(`Assets/UI/${t.attrs.id}.uxml`, uxml(content[0]));
361
+ if (!content[0])
362
+ continue;
363
+ out.files.set(`Assets/UI/${t.attrs.id}.uxml`, uxml(content[0]));
364
+ out.templates.set(t.attrs.id, `Assets/UI/${t.attrs.id}.uxml`);
347
365
  }
348
366
  return out;
349
367
  }
package/dist/stub.d.ts CHANGED
@@ -25,6 +25,11 @@ export interface ClassSource {
25
25
  }
26
26
  /** The class `name` declared in `code`, or undefined when it is not there. */
27
27
  export declare function readClass(code: string, file: string, name: string): ClassSource | undefined;
28
+ /**
29
+ * Every type alias a module declares, by name: `type Bonus = 'none' | 'laser'` — what a signature that
30
+ * names one means, wherever in the game it was declared.
31
+ */
32
+ export declare function typeAliases(code: string, file: string): Map<string, string>;
28
33
  /**
29
34
  * A module's code outside the classes named — its imports left out too: the interfaces, types,
30
35
  * constants and functions a behaviour's file holds beside it, which no stub carries.
@@ -36,10 +41,10 @@ export declare function moduleStub(file: string, code: string): string;
36
41
  * A TypeScript type as C#, where the type says it: `number` is `float`, a node is its `Transform`,
37
42
  * an element of the page is a `VisualElement`. Undefined when it does not.
38
43
  */
39
- export declare function csType(ts: string, classes: Map<string, string>): string | undefined;
44
+ export declare function csType(ts: string, classes: Map<string, string>, aliases?: Map<string, string>, depth?: number): string | undefined;
40
45
  /**
41
46
  * The C# class for a behaviour: `wired` are the fields its scenes and prefabs set — real fields, with
42
47
  * the C# the exporter already chose for them — and everything else comes from its TypeScript.
43
48
  */
44
- export declare function stubClass(name: string, file: string, source: ClassSource, wired: Map<string, string>, classes: Map<string, string>, outside?: string[]): string;
49
+ export declare function stubClass(name: string, file: string, source: ClassSource, wired: Map<string, string>, classes: Map<string, string>, outside?: string[], aliases?: Map<string, string>): string;
45
50
  export {};