@scenoco-three/unity 0.9.9 → 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/dist/stub.js ADDED
@@ -0,0 +1,324 @@
1
+ /**
2
+ * A behaviour's class, read from its TypeScript, as the outline of its C# port: every field, every
3
+ * method with a C# signature, and each method's TypeScript inside it as comments — so a port is
4
+ * written in place, method by method, with nothing to look up in the original.
5
+ *
6
+ * Only signatures are translated, and only where the type says what to write; the rest is the
7
+ * port's to decide. What a stub holds compiles as it is: a method returns its default until it is
8
+ * written, and a field whose C# type is not obvious stays a comment.
9
+ */
10
+ import { parseSync } from 'rolldown/utils';
11
+ /** Unity's messages, which a behaviour's hooks of the same name become: `update` is `Update`. */
12
+ const MESSAGES = new Set(('awake start update lateUpdate fixedUpdate onEnable onDisable onDestroy onValidate reset onApplicationPause ' +
13
+ 'onApplicationFocus onApplicationQuit onBecameVisible onBecameInvisible onCollisionEnter onCollisionStay onCollisionExit ' +
14
+ 'onTriggerEnter onTriggerStay onTriggerExit onCollisionEnter2D onCollisionStay2D onCollisionExit2D onTriggerEnter2D ' +
15
+ 'onTriggerStay2D onTriggerExit2D onControllerColliderHit onMouseDown onMouseUp onMouseEnter onMouseExit onMouseOver ' +
16
+ 'onMouseDrag onMouseUpAsButton onAnimatorMove onAnimatorIK onDrawGizmos onDrawGizmosSelected')
17
+ .split(' '));
18
+ /** Names that mean the same in Unity. */
19
+ /** The messages Unity calls with an argument; every other one takes none. */
20
+ const WITH_ARGUMENT = /^on(Collision|Trigger)(Enter|Stay|Exit)(2D)?$|^onControllerColliderHit$|^onApplication(Pause|Focus)$|^onAnimatorIK$/;
21
+ const SAME = new Set('Vector2 Vector3 Vector4 Quaternion Color Collision Collision2D Collider Collider2D Camera Light AudioClip Texture Texture2D Material Mesh Ray Plane Bounds'.split(' '));
22
+ const KEYWORDS = new Set(('abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum ' +
23
+ 'event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace ' +
24
+ 'new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc ' +
25
+ 'static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while')
26
+ .split(' '));
27
+ const pascal = (name) => name.charAt(0).toUpperCase() + name.slice(1);
28
+ const safe = (name) => (KEYWORDS.has(name) ? `@${name}` : name);
29
+ /** The class `name` declared in `code`, or undefined when it is not there. */
30
+ export function readClass(code, file, name) {
31
+ const { program, comments } = parseSync(file, code, { lang: file.endsWith('.tsx') ? 'tsx' : 'ts' });
32
+ const docBefore = (start) => {
33
+ const comment = comments.filter((c) => c.end <= start && c.type === 'Block' && c.value.startsWith('*')).at(-1);
34
+ if (!comment || code.slice(comment.end, start).trim() !== '')
35
+ return [];
36
+ return comment.value
37
+ .split('\n')
38
+ .map((line) => line.replace(/^\s*\*+ ?/, '').trimEnd())
39
+ .filter((line, i, all) => line !== '' || (i > 0 && i < all.length - 1));
40
+ };
41
+ const declaration = program.body
42
+ .map((s) => (s.type === 'ExportNamedDeclaration' || s.type === 'ExportDefaultDeclaration' ? s.declaration : s))
43
+ .find((s) => s?.type === 'ClassDeclaration' && s.id?.name === name);
44
+ if (!declaration)
45
+ return undefined;
46
+ const typeText = (t) => (t ? code.slice(t.typeAnnotation.start, t.typeAnnotation.end) : '');
47
+ const members = [];
48
+ for (const m of declaration.body.body) {
49
+ const key = m.key;
50
+ if (!key || (key.type !== 'Identifier' && key.type !== 'PrivateIdentifier'))
51
+ continue;
52
+ const base = {
53
+ name: key.name,
54
+ isStatic: Boolean(m.static),
55
+ access: (m.accessibility ?? (key.type === 'PrivateIdentifier' ? 'private' : 'public')),
56
+ text: code.slice(m.start, m.end),
57
+ doc: docBefore(m.start),
58
+ };
59
+ if (m.type === 'PropertyDefinition') {
60
+ members.push({ ...base, kind: 'field' });
61
+ }
62
+ else if (m.type === 'MethodDefinition') {
63
+ const fn = m.value;
64
+ const body = fn.body;
65
+ if (!body)
66
+ continue;
67
+ const params = fn.params.map((p) => {
68
+ const id = (p.type === 'AssignmentPattern' ? p.left : p.type === 'TSParameterProperty' ? p.parameter : p);
69
+ return { name: id.name ?? 'arg', type: typeText(id.typeAnnotation) };
70
+ });
71
+ let returns = typeText(fn.returnType);
72
+ if (!returns)
73
+ returns = fn.generator ? 'Generator' : fn.async ? 'Promise<void>' : returnsValue(body) ? 'unknown' : 'void';
74
+ else if (fn.async && !returns.startsWith('Promise'))
75
+ returns = `Promise<${returns}>`;
76
+ members.push({
77
+ ...base,
78
+ kind: m.kind,
79
+ head: code.slice(m.start, body.start).replace(/\s+/g, ' ').trim(),
80
+ body: dedent(code.slice(body.start + 1, body.end - 1)),
81
+ params,
82
+ returns,
83
+ });
84
+ }
85
+ }
86
+ const superClass = declaration.superClass;
87
+ return { doc: docBefore(declaration.start), base: superClass ? code.slice(superClass.start, superClass.end) : undefined, members };
88
+ }
89
+ /**
90
+ * A module's code outside the classes named — its imports left out too: the interfaces, types,
91
+ * constants and functions a behaviour's file holds beside it, which no stub carries.
92
+ */
93
+ export function outsideClasses(code, file, classes) {
94
+ const { program } = parseSync(file, code, { lang: file.endsWith('.tsx') ? 'tsx' : 'ts' });
95
+ const cut = [];
96
+ for (const statement of program.body) {
97
+ const inner = statement.declaration ?? statement;
98
+ if (statement.type === 'ImportDeclaration' || (inner.type === 'ClassDeclaration' && classes.includes(inner.id?.name)))
99
+ cut.push([statement.start, statement.end]);
100
+ }
101
+ let text = '';
102
+ let from = 0;
103
+ for (const [a, b] of cut) {
104
+ text += code.slice(from, a);
105
+ from = b;
106
+ }
107
+ text += code.slice(from);
108
+ // The doc comment of a class that was cut stays behind it: drop a comment left with nothing after it.
109
+ return text
110
+ .replace(/\/\*\*(?:(?!\*\/)[\s\S])*\*\/\s*(?=\n\s*\n|$)/g, '')
111
+ .replace(/\n{3,}/g, '\n\n')
112
+ .trim()
113
+ .split('\n')
114
+ .filter((_, i, lines) => lines.join('').trim() !== '');
115
+ }
116
+ /** A module no behaviour lives in, as a `.cs` holding its TypeScript for a port to write. */
117
+ export function moduleStub(file, code) {
118
+ return [
119
+ `// Ported from ${file.replace(/^\//, '')}, which holds no behaviour. Its TypeScript is below, as it is: port it as`,
120
+ '// C# where the game needs it — a static class for helpers, an enum for a union of names, a',
121
+ '// ScriptableObject for data a designer tunes — then delete the comment. Assets/SceNoCo/PORTING.md',
122
+ '// has the rules. Written by scenoco-unity once, never overwritten.',
123
+ '//',
124
+ ...code.replace(/\s+$/, '').split('\n').map((l) => (l ? `// ${l}` : '//')),
125
+ '',
126
+ ].join('\n');
127
+ }
128
+ /** Whether a function body returns a value — its own returns, not those of a function inside it. */
129
+ function returnsValue(body) {
130
+ const visit = (n) => {
131
+ if (!n || typeof n !== 'object')
132
+ return false;
133
+ if (Array.isArray(n))
134
+ return n.some(visit);
135
+ const node = n;
136
+ if (/Function|ArrowFunction|ClassBody/.test(node.type ?? ''))
137
+ return false;
138
+ if (node.type === 'ReturnStatement')
139
+ return node.argument != null;
140
+ return Object.values(node).some((v) => typeof v === 'object' && visit(v));
141
+ };
142
+ return body.body.some(visit);
143
+ }
144
+ function dedent(text) {
145
+ const lines = text.replace(/^\s*\n/, '').replace(/\s+$/, '').split('\n');
146
+ const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^\s*/.exec(l)[0].length));
147
+ return lines.map((l) => l.slice(Number.isFinite(indent) ? indent : 0).trimEnd());
148
+ }
149
+ /**
150
+ * A TypeScript type as C#, where the type says it: `number` is `float`, a node is its `Transform`,
151
+ * an element of the page is a `VisualElement`. Undefined when it does not.
152
+ */
153
+ export function csType(ts, classes) {
154
+ const t = ts.trim().replace(/^readonly\s+/, '');
155
+ if (!t)
156
+ return undefined;
157
+ const parts = splitTop(t, '|').map((p) => p.trim()).filter((p) => p !== 'null' && p !== 'undefined');
158
+ if (parts.length > 1) {
159
+ if (parts.every((p) => /^(['"]).*\1$/.test(p)))
160
+ return 'string';
161
+ if (parts.every((p) => /^-?\d/.test(p)))
162
+ return 'float';
163
+ return undefined;
164
+ }
165
+ const one = parts[0] ?? '';
166
+ if (one.startsWith('(') && one.endsWith(')'))
167
+ return csType(one.slice(1, -1), classes);
168
+ if (one.endsWith('[]')) {
169
+ const inner = csType(one.slice(0, -2), classes);
170
+ return inner && inner !== 'void' ? `${inner}[]` : undefined;
171
+ }
172
+ if (/^(['"]).*\1$/.test(one))
173
+ return 'string';
174
+ if (/^-?\d/.test(one))
175
+ return 'float';
176
+ if (one === 'number')
177
+ return 'float';
178
+ if (one === 'boolean' || one === 'true' || one === 'false')
179
+ return 'bool';
180
+ if (one === 'string')
181
+ return 'string';
182
+ if (one === 'void' || one === 'undefined')
183
+ return 'void';
184
+ const generic = /^(\w+)(?:<(.*)>)?$/.exec(one);
185
+ if (!generic)
186
+ return undefined;
187
+ const [, name, args] = generic;
188
+ if (name === 'Array' && args)
189
+ return csType(`${args}[]`, classes);
190
+ if (name === 'Generator' || name === 'Iterator' || name === 'IterableIterator')
191
+ return 'IEnumerator';
192
+ if (name === 'Promise') {
193
+ const inner = args ? csType(args, classes) : 'void';
194
+ return inner === 'void' ? 'Awaitable' : inner ? `Awaitable<${inner}>` : undefined;
195
+ }
196
+ if (SAME.has(name))
197
+ return name;
198
+ if (name === 'Object3D' || name === 'Group' || name === 'Mesh' || name === 'Scene')
199
+ return 'Transform';
200
+ if (name === 'Behaviour')
201
+ return 'MonoBehaviour';
202
+ if (/^HTML\w*Element$/.test(name))
203
+ return 'VisualElement';
204
+ return classes.get(name);
205
+ }
206
+ /** `text` split at `separator` where it is not inside brackets of any kind. */
207
+ function splitTop(text, separator) {
208
+ const out = [];
209
+ let depth = 0;
210
+ let from = 0;
211
+ for (let i = 0; i < text.length; i++) {
212
+ const c = text[i];
213
+ if ('<([{'.includes(c))
214
+ depth++;
215
+ else if ('>)]}'.includes(c))
216
+ depth--;
217
+ else if (c === separator && depth === 0) {
218
+ out.push(text.slice(from, i));
219
+ from = i + 1;
220
+ }
221
+ }
222
+ out.push(text.slice(from));
223
+ return out;
224
+ }
225
+ /**
226
+ * The C# class for a behaviour: `wired` are the fields its scenes and prefabs set — real fields, with
227
+ * the C# the exporter already chose for them — and everything else comes from its TypeScript.
228
+ */
229
+ export function stubClass(name, file, source, wired, classes, outside = []) {
230
+ const lines = [];
231
+ const comment = (text, indent) => text.map((l) => (l ? `${indent}// ${l}` : `${indent}//`));
232
+ const base = source.base === 'Behaviour' || !source.base ? 'MonoBehaviour' : (classes.get(source.base) ?? 'MonoBehaviour');
233
+ lines.push(...comment(source.doc, ''));
234
+ if (source.doc.length)
235
+ lines.push('//');
236
+ lines.push(`// Ported from ${file.replace(/^\//, '')}. Each member below holds its TypeScript as comments: write the C# in`, '// its place, then delete the comment. Keep the field names: the prefabs are wired by them.', '// Assets/SceNoCo/PORTING.md has the rules. Written by scenoco-unity once, never overwritten.');
237
+ if (name !== source.base && base === 'MonoBehaviour' && source.base && source.base !== 'Behaviour') {
238
+ lines.push(`// In TypeScript it extends ${source.base}, which has no C# class here.`);
239
+ }
240
+ lines.push(`public class ${name} : ${base}`, '{');
241
+ const body = [];
242
+ const declared = new Set(source.members.filter((m) => m.kind === 'field').map((m) => m.name));
243
+ // Wired fields an ancestor declares: still real fields, so the prefabs keep their values.
244
+ for (const [field, line] of wired)
245
+ if (!declared.has(field))
246
+ body.push([line]);
247
+ for (const m of source.members) {
248
+ const block = comment(m.doc, ' ');
249
+ if (m.kind === 'field') {
250
+ const real = wired.get(m.name);
251
+ if (real)
252
+ block.push(real);
253
+ else
254
+ block.push(...comment(m.text.split('\n').map((l) => l.trim()), ' '));
255
+ }
256
+ else if (m.kind === 'constructor') {
257
+ block.push(' // A MonoBehaviour has no constructor: what this one does belongs in Awake.', ...comment([`${m.head} {`, ...m.body.map((l) => ` ${l}`), '}'], ' '));
258
+ }
259
+ else if (m.kind === 'get' || m.kind === 'set') {
260
+ continue;
261
+ }
262
+ else {
263
+ block.push(...method(m, classes));
264
+ }
265
+ body.push(block);
266
+ }
267
+ body.push(...properties(source.members, classes));
268
+ lines.push(...body.flatMap((b, i) => (i ? ['', ...b] : b)), '}', '');
269
+ if (outside.length) {
270
+ lines.push(`// Outside the class, in ${file.replace(/^\//, '')}: port it where the game needs it — an enum, a static class, a`, '// ScriptableObject — then delete the comment.', '//', ...outside.map((l) => (l ? `// ${l}` : '//')), '');
271
+ }
272
+ const usings = ['using System.Collections;', 'using UnityEngine;'];
273
+ if (lines.some((l) => !l.trimStart().startsWith('//') && l.includes('VisualElement')))
274
+ usings.push('using UnityEngine.UIElements;');
275
+ return [...usings, '', ...lines].join('\n');
276
+ }
277
+ function method(m, classes) {
278
+ const message = MESSAGES.has(m.name) && !m.isStatic;
279
+ const returns = csType(m.returns, classes) ?? 'object';
280
+ // Core hands `update` the frame's time; Unity's Update takes nothing and reads Time.deltaTime.
281
+ const dropped = message && !WITH_ARGUMENT.test(m.name) ? m.params : [];
282
+ const params = (dropped.length ? [] : m.params).map((p) => `${csType(p.type, classes) ?? 'object'} ${safe(p.name)}`).join(', ');
283
+ const modifiers = message ? '' : `${m.access} ${m.isStatic ? 'static ' : ''}`;
284
+ const placeholder = returns === 'void' ? [] : returns === 'IEnumerator' ? [' yield break;'] : [' return default;'];
285
+ return [
286
+ ` ${modifiers}${returns} ${pascal(m.name)}(${params})`,
287
+ ' {',
288
+ ...dropped.map((p) => ` // Unity passes no ${p.name}: ${m.name === 'fixedUpdate' ? 'Time.fixedDeltaTime' : 'Time.deltaTime'} is the frame's time.`),
289
+ ` // ${m.head} {`,
290
+ ...m.body.map((l) => (l ? ` // ${l}` : ' //')),
291
+ ' // }',
292
+ ...placeholder,
293
+ ' }',
294
+ ];
295
+ }
296
+ /** Getters and setters as C# properties, one per name. */
297
+ function properties(members, classes) {
298
+ const out = [];
299
+ const names = [...new Set(members.filter((m) => m.kind === 'get' || m.kind === 'set').map((m) => m.name))];
300
+ for (const name of names) {
301
+ const get = members.find((m) => m.kind === 'get' && m.name === name);
302
+ const set = members.find((m) => m.kind === 'set' && m.name === name);
303
+ const first = get ?? set;
304
+ const type = csType(get?.returns ?? set?.params?.[0]?.type ?? '', classes) ?? 'object';
305
+ const accessor = (m, word, placeholder) => [
306
+ ` ${word}`,
307
+ ' {',
308
+ ` // ${m.head} {`,
309
+ ...m.body.map((l) => (l ? ` // ${l}` : ' //')),
310
+ ' // }',
311
+ ...placeholder,
312
+ ' }',
313
+ ];
314
+ out.push([
315
+ ...first.doc.map((l) => (l ? ` // ${l}` : ' //')),
316
+ ` ${first.access} ${first.isStatic ? 'static ' : ''}${type} ${pascal(name)}`,
317
+ ' {',
318
+ ...(get ? accessor(get, 'get', [' return default;']) : []),
319
+ ...(set ? accessor(set, 'set', []) : []),
320
+ ' }',
321
+ ]);
322
+ }
323
+ return out;
324
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenoco-three/unity",
3
- "version": "0.9.9",
3
+ "version": "1.0.0",
4
4
  "description": "Export a SceNoCo game's prefabs, scenes, meshes and materials into a Unity project: nested prefabs, shared materials, behaviours as MonoBehaviours with their fields wired.",
5
5
  "keywords": [
6
6
  "three",
@@ -50,10 +50,11 @@
50
50
  "typecheck": "tsc --noEmit -p tsconfig.json"
51
51
  },
52
52
  "dependencies": {
53
- "playwright-core": "^1.62.1"
53
+ "playwright-core": "^1.62.1",
54
+ "rolldown": "^1.0.3"
54
55
  },
55
56
  "peerDependencies": {
56
- "@scenoco-three/core": "^0.9.9",
57
+ "@scenoco-three/core": "^1.0.0",
57
58
  "vite": ">=6"
58
59
  }
59
60
  }
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "SceNoCo.Driver",
3
+ "rootNamespace": "SceNoCo.Driver",
4
+ "references": [
5
+ "Unity.Pipeline.Attributes",
6
+ "Unity.InputSystem"
7
+ ],
8
+ "includePlatforms": [
9
+ "Editor"
10
+ ],
11
+ "excludePlatforms": [],
12
+ "allowUnsafeCode": false,
13
+ "overrideReferences": false,
14
+ "precompiledReferences": [],
15
+ "autoReferenced": false,
16
+ "defineConstraints": [
17
+ "SCENOCO_PIPELINE"
18
+ ],
19
+ "versionDefines": [
20
+ {
21
+ "name": "com.unity.pipeline",
22
+ "expression": "0.0.0",
23
+ "define": "SCENOCO_PIPELINE"
24
+ },
25
+ {
26
+ "name": "com.unity.inputsystem",
27
+ "expression": "1.0.0",
28
+ "define": "SCENOCO_INPUT_SYSTEM"
29
+ }
30
+ ],
31
+ "noEngineReferences": false
32
+ }