@kubohiroya/turbowarp-aframe 0.3.0 → 0.4.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.
@@ -24,14 +24,16 @@ src/config.ts + src/block-definitions.json
24
24
 
25
25
  ## version付きruntime capability
26
26
 
27
- 機能拡張は`Scratch.vm.runtime.turbowarpAFrameCapability`を公開します。version 1は、`loadTemplate`、`createFromTemplate`、`setPosition`、`setRotation`、`emitEvent`、`deleteSelector`、`countSelector`だけを持つ狭い型付きportです。
27
+ 機能拡張は`Scratch.vm.runtime.turbowarpAFrameCapability`を公開します。version 2は、`loadTemplate`、`createFromTemplate`、`setPosition`、`setRotation`、`emitEvent`、`deleteSelector`、`countSelector`に、`loadVrm`、`setVrmBoneRotation`、`vrmBoneNames`、`vrmStatus`を加えた、freezeされた狭い型付きportです。scene操作だけを持っていたversion 1は、version 2と並べて残さず0.4.0で撤去しました。正しく保つ契約を1つにするためです。
28
28
 
29
29
  各port methodは対応するblock handlerへ委譲します。そのため、block呼び出しと複合機能拡張からの呼び出しは、cast、validation、selector matching、event queue、機能拡張所有のscene stateを共有します。portはDOM element、A-Frame/Three.js object、glTF内部実装を公開しません。
30
30
 
31
- consumerは利用前に`requireVersion(1)`を呼ぶ必要があります。未対応versionは互換fallbackを試さず例外になります。`dispose()`はruntimeからcapabilityを削除し、実行中のanimation playbackを停止し、scene hostを除去して、dispose前にconsumerが保持した参照も恒久的に無効化します。disposeの反復呼び出しは安全です。
31
+ consumerは利用前に`requireVersion(2)`を呼ぶ必要があります。1を含むそれ以外のversionは、互換fallbackを試さず例外になります。`dispose()`はruntimeからcapabilityを削除し、実行中のanimation playbackを停止し、scene hostを除去して、dispose前にconsumerが保持した参照も恒久的に無効化します。disposeの反復呼び出しは安全です。
32
32
 
33
33
  ## シーン初期化
34
34
 
35
+ `createScene`はsceneを作る前に、ページにA-Frame 1.8.0があることを確かめます。なければ`https://cdn.jsdelivr.net/npm/aframe@1.8.0/dist/aframe-v1.8.0.min.js`のscriptを、SHA-384のsubresource integrityと`crossorigin="anonymous"`付きで追加して待ちます。CDN上のファイルが変わっていれば拒否され、blockはA-Frameの準備ができてから完了します。同時に作られたsceneは1回の読み込みを共有し、失敗またはtimeout(30秒)した読み込みはscriptを取り除いて、次の呼び出しで再試行できるようにします。ページにA-Frame 1.8.0がすでにあれば何も読み込まず、自前のコピーを配信するオフライン会場でも動きます。ほかのversionがあれば拒否します。2つ目のA-Frameは並べて動かせず、three-vrmは1.8.0のThree.jsでしか確かめていないためです。A-Frameはbundleしません。
36
+
35
37
  `createScene` は root の `#scene` ノードを作り、ブラウザ DOM がある場合は `#tw-aframe-root > a-scene` を作成します。host は最初に検出できた TurboWarp stage wrapper または canvas の親へ mount し、stage らしい要素が見つからない場合だけ `document.body` に fallback します。
36
38
 
37
39
  初期 layer は文字列です。Book/API 側で語彙を調整しても block shape を変えずに済むようにしています。
@@ -111,7 +113,7 @@ track の `times` と `values` は comma または whitespace 区切りの numbe
111
113
 
112
114
  single-keyframe helper block はブロック優先の authoring path です。`.position`、`.scale`、`.quaternion` の keyframe を 1 つずつ挿入し、time 順に並べ、同じ clip、path、time の keyframe は後から追加した値で置き換えます。comma-separated full-track block は、Three.js 形式の配列をすでに持っている advanced user 向けに残します。
113
115
 
114
- 再生は Scratch sprite ではなく一致した node に紐づきます。browser DOM、A-Frame、`AFRAME.THREE` が利用可能な場合、`play 3D animation clip` は対象 node の root `object3D` ごとに `AnimationMixer` を作成し、clip action を開始し、scene 上の小さな A-Frame bridge component から active mixer を更新します。glTF bone、child object path、material property、blending、cross-fade control は初期実装の外に置きます。DOM のない test environment では、Three.js object を作らず registry と validation を検証できます。
116
+ 再生は Scratch sprite ではなく一致した node に紐づきます。browser DOM、A-Frame、`AFRAME.THREE` が利用可能な場合、`play 3D animation clip` は対象 node の root `object3D` ごとに `AnimationMixer` を作成し、clip action を開始し、scene 上の小さな A-Frame bridge component から active mixer を更新します。glTF bone、child object path、material property、blending、cross-fade control は初期実装の外に置きます。VRMのヒューマノイドのボーンは、animation clipではなくVRMのブロックで回します。DOM のない test environment では、Three.js object を作らず registry と validation を検証できます。
115
117
 
116
118
  既存の `rotation` ブロックは A-Frame attribute を書くため degree-based のまま維持します。Quaternion animation は Three.js object state を使うため、A-Frame Euler attribute rotation とは別の機能として扱います。
117
119
 
@@ -24,14 +24,16 @@ The generated JavaScript bundle is an unsandboxed TurboWarp extension. The manif
24
24
 
25
25
  ## Versioned Runtime Capability
26
26
 
27
- The extension publishes `Scratch.vm.runtime.turbowarpAFrameCapability`. Version 1 is a narrow typed port containing `loadTemplate`, `createFromTemplate`, `setPosition`, `setRotation`, `emitEvent`, `deleteSelector`, and `countSelector`.
27
+ The extension publishes `Scratch.vm.runtime.turbowarpAFrameCapability`. Version 2 is a narrow typed, frozen port containing `loadTemplate`, `createFromTemplate`, `setPosition`, `setRotation`, `emitEvent`, `deleteSelector`, and `countSelector`, plus `loadVrm`, `setVrmBoneRotation`, `vrmBoneNames`, and `vrmStatus`. Version 1, which had only the scene operations, was removed in 0.4.0 rather than kept beside version 2, so there is a single contract to keep correct.
28
28
 
29
29
  Each port method delegates to the corresponding block handler. Consequently, block calls and composite-extension calls share casting, validation, selector matching, event queuing, and the extension-owned scene state. The port never exposes DOM elements, A-Frame/Three.js objects, or glTF internals.
30
30
 
31
- Consumers must call `requireVersion(1)` before use. An unsupported version throws instead of attempting compatibility fallback. `dispose()` removes the capability from the runtime, stops active animation playbacks, removes the scene host, and permanently invalidates references that a consumer retained before disposal. Repeated disposal is safe.
31
+ Consumers must call `requireVersion(2)` before use. Any other version, including 1, throws instead of attempting compatibility fallback. `dispose()` removes the capability from the runtime, stops active animation playbacks, removes the scene host, and permanently invalidates references that a consumer retained before disposal. Repeated disposal is safe.
32
32
 
33
33
  ## Scene initialization
34
34
 
35
+ Before building the scene, `createScene` makes sure A-Frame 1.8.0 is on the page. It adds a script for `https://cdn.jsdelivr.net/npm/aframe@1.8.0/dist/aframe-v1.8.0.min.js` with a SHA-384 subresource integrity hash and `crossorigin="anonymous"`, so a changed file on the CDN is refused, and waits for it; the block resolves only after A-Frame is ready. Concurrent scenes share one load, and a failed or timed-out load (30 s) removes its script so the next call can try again. A page that already has A-Frame 1.8.0 loads nothing, which keeps an offline venue that serves its own copy working. Any other version on the page is refused, because a second A-Frame cannot run beside it and three-vrm is verified on the Three.js of 1.8.0 only. A-Frame is never bundled.
36
+
35
37
  `createScene` creates a root `#scene` node and, when a browser DOM exists, a `#tw-aframe-root > a-scene` host. The host is mounted inside the first detected TurboWarp stage wrapper or canvas parent, falling back to `document.body` only when no stage-like element is found.
36
38
 
37
39
  The initial layer values are strings so the book/API can refine the vocabulary without changing the block shape:
@@ -111,7 +113,7 @@ Track `times` and `values` are passed as comma- or whitespace-separated number l
111
113
 
112
114
  Single-keyframe helper blocks provide the block-first authoring path. They insert one `.position`, `.scale`, or `.quaternion` keyframe at a time, keep keyframes sorted, and replace an existing keyframe when the clip, path, and time match. The comma-separated full-track blocks remain available for advanced users who already have Three.js-style arrays.
113
115
 
114
- Playback is attached to matching nodes, not Scratch sprites. When browser DOM, A-Frame, and `AFRAME.THREE` are available, `play 3D animation clip` creates an `AnimationMixer` for each target node root `object3D`, starts a clip action, and updates active mixers through a small A-Frame bridge component on the scene. glTF bones, child object paths, material properties, blending, and cross-fade controls are left outside the first implementation. In non-DOM test environments, the registry and validation behavior remain testable without constructing Three.js objects.
116
+ Playback is attached to matching nodes, not Scratch sprites. When browser DOM, A-Frame, and `AFRAME.THREE` are available, `play 3D animation clip` creates an `AnimationMixer` for each target node root `object3D`, starts a clip action, and updates active mixers through a small A-Frame bridge component on the scene. glTF bones, child object paths, material properties, blending, and cross-fade controls are left outside the first implementation. VRM humanoid bones are turned by the VRM blocks rather than by animation clips. In non-DOM test environments, the registry and validation behavior remain testable without constructing Three.js objects.
115
117
 
116
118
  The existing `rotation` block remains degree-based because it writes A-Frame attributes. Quaternion animation uses Three.js object state and should be documented as separate from A-Frame Euler attribute rotation.
117
119
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-aframe",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "A TurboWarp extension for declarative A-Frame scene graphs.",
5
5
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
6
  "license": "MPL-2.0",
@@ -31,7 +31,8 @@
31
31
  "src/",
32
32
  "README.md",
33
33
  "README.ja.md",
34
- "LICENSE"
34
+ "LICENSE",
35
+ "THIRD_PARTY_NOTICES.md"
35
36
  ],
36
37
  "publishConfig": {
37
38
  "access": "public",
@@ -58,8 +59,11 @@
58
59
  "devDependencies": {
59
60
  "@eslint/js": "^9.39.5",
60
61
  "@kubohiroya/vite-plugin-turbowarp-extension": "0.4.0",
62
+ "@pixiv/three-vrm": "3.5.5",
61
63
  "@types/node": "^24.13.3",
64
+ "@types/three": "0.184.0",
62
65
  "eslint": "^9.39.5",
66
+ "super-three": "0.184.0",
63
67
  "typescript": "^5.9.3",
64
68
  "typescript-eslint": "^8.66.0",
65
69
  "vite": "^8.2.2",
@@ -0,0 +1,74 @@
1
+ /** The A-Frame this extension is built and tested against, including three-vrm on its Three.js. */
2
+ export const aframeVersion = '1.8.0';
3
+ export const aframeUrl = `https://cdn.jsdelivr.net/npm/aframe@${aframeVersion}/dist/aframe-v${aframeVersion}.min.js`;
4
+ /** Subresource integrity of `aframeUrl`, so a changed file on the CDN is refused. */
5
+ export const aframeIntegrity =
6
+ 'sha384-d2HJ2eWTxYenz2Vcmsy7gDZW7G2Gq51k1M15G7vv2O/S60nSNYZVjtgGzPnd3sG+';
7
+ const loadTimeoutMs = 30_000;
8
+
9
+ interface AFrameGlobal {
10
+ AFRAME?: {version?: string};
11
+ __twAframeLoading?: Promise<void>;
12
+ }
13
+
14
+ /**
15
+ * Makes sure A-Frame 1.8.0 is on the page, loading it from jsDelivr when it is not.
16
+ *
17
+ * A page that already has A-Frame 1.8.0, such as an offline venue that serves its own copy,
18
+ * loads nothing. Any other A-Frame version is refused, because a second copy cannot be
19
+ * loaded beside it and three-vrm is verified on 1.8.0 only. Without a document, as in tests
20
+ * and non-browser runtimes, the scene graph works without A-Frame and nothing is loaded.
21
+ */
22
+ export async function ensureAFrame(): Promise<void> {
23
+ const state = globalThis as AFrameGlobal;
24
+ if (state.AFRAME !== undefined) {
25
+ requireVersion(state.AFRAME);
26
+ return;
27
+ }
28
+ const head = typeof document === 'undefined' ? undefined : document.head;
29
+ if (head === undefined || head === null) return;
30
+ state.__twAframeLoading ??= load(head).catch((error: unknown) => {
31
+ delete state.__twAframeLoading;
32
+ throw error;
33
+ });
34
+ await state.__twAframeLoading;
35
+ }
36
+
37
+ function load(head: HTMLElement): Promise<void> {
38
+ return new Promise((resolve, reject) => {
39
+ const script = document.createElement('script');
40
+ const fail = (reason: string) => {
41
+ clearTimeout(timer);
42
+ script.remove();
43
+ reject(new Error(`Could not load A-Frame ${aframeVersion} from ${aframeUrl}: ${reason}`));
44
+ };
45
+ const timer = setTimeout(() => fail(`no response in ${loadTimeoutMs / 1000} s`), loadTimeoutMs);
46
+ script.src = aframeUrl;
47
+ script.integrity = aframeIntegrity;
48
+ script.crossOrigin = 'anonymous';
49
+ script.onload = () => {
50
+ clearTimeout(timer);
51
+ const loaded = (globalThis as AFrameGlobal).AFRAME;
52
+ if (loaded === undefined) {
53
+ reject(new Error(`A-Frame ${aframeVersion} loaded but did not define AFRAME.`));
54
+ return;
55
+ }
56
+ try {
57
+ requireVersion(loaded);
58
+ resolve();
59
+ } catch (error) {
60
+ reject(error instanceof Error ? error : new Error(String(error)));
61
+ }
62
+ };
63
+ script.onerror = () => fail('the request failed or the file did not match its integrity hash');
64
+ head.append(script);
65
+ });
66
+ }
67
+
68
+ function requireVersion(aframe: {version?: string}): void {
69
+ if (aframe.version !== aframeVersion) {
70
+ throw new Error(
71
+ `A-Frame ${aframe.version ?? '(unknown version)'} is already on the page; TurboWarp-A-Frame needs ${aframeVersion}.`
72
+ );
73
+ }
74
+ }
@@ -5,7 +5,7 @@
5
5
  "opcode": "createScene",
6
6
  "blockType": "COMMAND",
7
7
  "text": "create 3D scene with layer [LAYER] mode [MODE]",
8
- "description": "Initializes the A-Frame scene host and emits the scene ready event.",
8
+ "description": "Loads A-Frame 1.8.0 from jsDelivr when the page does not have it, initializes the A-Frame scene host, and emits the scene ready event.",
9
9
  "arguments": {
10
10
  "LAYER": {"type": "STRING", "defaultValue": "above-stage"},
11
11
  "MODE": {"type": "STRING", "defaultValue": "3d"}
@@ -324,6 +324,47 @@
324
324
  "CLIP": {"type": "STRING", "defaultValue": "wave"},
325
325
  "SELECTOR": {"type": "STRING", "defaultValue": "#leftArm"}
326
326
  }
327
+ },
328
+ {
329
+ "opcode": "loadVrm",
330
+ "blockType": "COMMAND",
331
+ "text": "load VRM [URL] onto [SELECTOR]",
332
+ "description": "Loads a VRM avatar with three-vrm on the A-Frame Three.js and attaches it to the first matching node. The block waits until the model is ready.",
333
+ "arguments": {
334
+ "URL": {"type": "STRING", "defaultValue": "avatar.vrm"},
335
+ "SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
336
+ }
337
+ },
338
+ {
339
+ "opcode": "setVrmBoneRotation",
340
+ "blockType": "COMMAND",
341
+ "text": "set VRM [SELECTOR] bone [BONE] rotation x [X] y [Y] z [Z]",
342
+ "description": "Sets the Euler rotation in degrees of a normalized VRM humanoid bone, relative to the T-pose, on every matching node whose VRM is ready.",
343
+ "arguments": {
344
+ "SELECTOR": {"type": "STRING", "defaultValue": "#avatar"},
345
+ "BONE": {"type": "STRING", "defaultValue": "leftUpperArm"},
346
+ "X": {"type": "NUMBER", "defaultValue": 0},
347
+ "Y": {"type": "NUMBER", "defaultValue": 0},
348
+ "Z": {"type": "NUMBER", "defaultValue": -60}
349
+ }
350
+ },
351
+ {
352
+ "opcode": "vrmBoneNames",
353
+ "blockType": "REPORTER",
354
+ "text": "VRM [SELECTOR] humanoid bones",
355
+ "description": "Returns the humanoid bone names of the first matching node's VRM as a JSON array.",
356
+ "arguments": {
357
+ "SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
358
+ }
359
+ },
360
+ {
361
+ "opcode": "vrmState",
362
+ "blockType": "REPORTER",
363
+ "text": "VRM [SELECTOR] state",
364
+ "description": "Returns none, loading, ready, or error with its reason for the first matching node.",
365
+ "arguments": {
366
+ "SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
367
+ }
327
368
  }
328
369
  ]
329
370
  }
package/src/extension.ts CHANGED
@@ -3,8 +3,11 @@ import definitions from './block-definitions.json';
3
3
  import {
4
4
  createRuntimeCapability,
5
5
  runtimeCapabilityKey,
6
- type AFrameRuntimeCapabilityV1
6
+ type AFrameRuntimeCapabilityV2,
7
+ type AFrameVrmStatus
7
8
  } from './runtime-capability.js';
9
+ import {ensureAFrame} from './aframe-loader.js';
10
+ import {VrmAvatars, type VrmThreeApi} from './vrm.js';
8
11
 
9
12
  type BlockTypeName = 'COMMAND' | 'REPORTER' | 'HAT' | 'BOOLEAN';
10
13
  type ArgumentTypeName = 'STRING' | 'NUMBER' | 'BOOLEAN';
@@ -110,6 +113,11 @@ type AFrameApi = {
110
113
  registerComponent(name: string, definition: unknown): void;
111
114
  };
112
115
 
116
+ interface VrmHostElement {
117
+ object3D?: {add(object: object): void};
118
+ setObject3D?(name: string, object: object): void;
119
+ }
120
+
113
121
  const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
114
122
  const ROOT_ID = 'scene';
115
123
  const DOM_EVENT_TYPES = ['click', 'tap', 'pointerenter', 'pointerleave'] as const;
@@ -135,8 +143,9 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
135
143
  private rootElement: Element | null = null;
136
144
  private sceneReadyPending = false;
137
145
  private lastEvent: SceneEvent | null = null;
138
- private readonly runtimeCapability: AFrameRuntimeCapabilityV1;
146
+ private readonly runtimeCapability: AFrameRuntimeCapabilityV2;
139
147
  private disposed = false;
148
+ private readonly vrms = new VrmAvatars(() => this.getThree() as unknown as VrmThreeApi | null);
140
149
 
141
150
  public constructor() {
142
151
  this.resetGraph();
@@ -152,7 +161,12 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
152
161
  emitEvent: (type, selector, data) =>
153
162
  this.emitEvent({TYPE: type, SELECTOR: selector, DATA: data}),
154
163
  deleteSelector: (selector) => this.deleteSelector({SELECTOR: selector}),
155
- countSelector: (selector) => this.countSelector({SELECTOR: selector})
164
+ countSelector: (selector) => this.countSelector({SELECTOR: selector}),
165
+ loadVrm: (url, selector) => this.loadVrm({URL: url, SELECTOR: selector}),
166
+ setVrmBoneRotation: (selector, bone, x, y, z) =>
167
+ this.setVrmBoneRotation({SELECTOR: selector, BONE: bone, X: x, Y: y, Z: z}),
168
+ vrmBoneNames: (selector) => this.vrmBoneNamesFor(Scratch.Cast.toString(selector)),
169
+ vrmStatus: (selector) => this.vrmStatusFor(Scratch.Cast.toString(selector))
156
170
  },
157
171
  () => this.assertActive()
158
172
  );
@@ -170,7 +184,8 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
170
184
  };
171
185
  }
172
186
 
173
- public createScene(args: {LAYER: unknown; MODE: unknown}): void {
187
+ public async createScene(args: {LAYER: unknown; MODE: unknown}): Promise<void> {
188
+ await ensureAFrame();
174
189
  this.sceneOptions = {
175
190
  layer: Scratch.Cast.toString(args.LAYER) || 'above-stage',
176
191
  mode: Scratch.Cast.toString(args.MODE) || '3d'
@@ -500,8 +515,48 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
500
515
  });
501
516
  }
502
517
 
518
+ public async loadVrm(args: {URL: unknown; SELECTOR: unknown}): Promise<void> {
519
+ const selector = Scratch.Cast.toString(args.SELECTOR);
520
+ const node = this.firstMatch(selector);
521
+ if (node === undefined) throw new Error(`No A-Frame node matches: ${selector}`);
522
+ const element = node.element as (Element & VrmHostElement) | null;
523
+ if (element === null) throw new Error('VRM avatars need a scene in the browser.');
524
+ this.ensureAnimationTickBridge();
525
+ await this.vrms.load(node.id, Scratch.Cast.toString(args.URL), (scene) => {
526
+ if (element.setObject3D !== undefined) {
527
+ element.setObject3D('vrm', scene);
528
+ } else {
529
+ element.object3D?.add(scene);
530
+ }
531
+ });
532
+ }
533
+
534
+ public setVrmBoneRotation(args: {
535
+ SELECTOR: unknown;
536
+ BONE: unknown;
537
+ X: unknown;
538
+ Y: unknown;
539
+ Z: unknown;
540
+ }): void {
541
+ const bone = Scratch.Cast.toString(args.BONE).trim();
542
+ const rotation = this.argsToVec3(args);
543
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
544
+ if (this.vrms.state(node.id) !== 'ready') continue;
545
+ this.vrms.setBoneRotation(node.id, bone, rotation);
546
+ }
547
+ }
548
+
549
+ public vrmBoneNames(args: {SELECTOR: unknown}): string {
550
+ return JSON.stringify(this.vrmBoneNamesFor(Scratch.Cast.toString(args.SELECTOR)));
551
+ }
552
+
553
+ public vrmState(args: {SELECTOR: unknown}): string {
554
+ const {state, error} = this.vrmStatusFor(Scratch.Cast.toString(args.SELECTOR));
555
+ return state === 'error' ? `error: ${error}` : state;
556
+ }
557
+
503
558
  public testStepAnimations(args: {DELTA: unknown}): void {
504
- this.updateAnimationMixers(Scratch.Cast.toNumber(args.DELTA) / 1000);
559
+ this.updateFrame(Scratch.Cast.toNumber(args.DELTA) / 1000);
505
560
  }
506
561
 
507
562
  public snapshot(): Record<string, unknown> {
@@ -545,6 +600,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
545
600
  for (const key of [...this.animationPlaybacks.keys()]) {
546
601
  this.stopPlayback(key, true);
547
602
  }
603
+ this.vrms.clear();
548
604
  this.rootElement?.parentElement?.remove();
549
605
  this.rootElement = null;
550
606
  const runtime = Scratch.vm?.runtime;
@@ -563,6 +619,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
563
619
  for (const key of [...this.animationPlaybacks.keys()]) {
564
620
  this.stopPlayback(key, true);
565
621
  }
622
+ this.vrms.clear();
566
623
  this.nodes.clear();
567
624
  this.nodes.set(ROOT_ID, {
568
625
  id: ROOT_ID,
@@ -627,6 +684,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
627
684
  }
628
685
  node.element?.remove();
629
686
  this.nodes.delete(id);
687
+ this.vrms.remove(id);
630
688
  for (const key of [...this.animationPlaybacks.keys()]) {
631
689
  if (key.startsWith(`${id}:`)) {
632
690
  this.stopPlayback(key, true);
@@ -1034,6 +1092,22 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
1034
1092
  }
1035
1093
  }
1036
1094
 
1095
+ private vrmBoneNamesFor(selector: string): string[] {
1096
+ const node = this.firstMatch(selector);
1097
+ return node === undefined ? [] : this.vrms.boneNames(node.id);
1098
+ }
1099
+
1100
+ private vrmStatusFor(selector: string): AFrameVrmStatus {
1101
+ const node = this.firstMatch(selector);
1102
+ if (node === undefined) return {state: 'none', error: ''};
1103
+ return {state: this.vrms.state(node.id), error: this.vrms.error(node.id)};
1104
+ }
1105
+
1106
+ private updateFrame(deltaTime: number): void {
1107
+ this.updateAnimationMixers(deltaTime);
1108
+ if (Number.isFinite(deltaTime) && deltaTime >= 0) this.vrms.update(deltaTime);
1109
+ }
1110
+
1037
1111
  private updateAnimationMixers(deltaTime: number): void {
1038
1112
  if (!Number.isFinite(deltaTime) || deltaTime < 0) return;
1039
1113
  for (const playback of this.animationPlaybacks.values()) {
@@ -1054,7 +1128,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
1054
1128
  schema: {id: {type: 'string'}},
1055
1129
  tick(this: {data: {id: string}}, _time: number, timeDelta: number) {
1056
1130
  const extension = animationRuntimeRegistry().get(this.data.id);
1057
- extension?.updateAnimationMixers(timeDelta / 1000);
1131
+ extension?.updateFrame(timeDelta / 1000);
1058
1132
  }
1059
1133
  });
1060
1134
  }
package/src/globals.d.ts CHANGED
@@ -26,3 +26,13 @@ interface ScratchApi {
26
26
  }
27
27
 
28
28
  declare const Scratch: ScratchApi;
29
+
30
+ declare module 'virtual:three-vrm-factory' {
31
+ export function createThreeVrm(THREE: unknown): {
32
+ VRMLoaderPlugin: new (parser: never) => unknown;
33
+ VRMUtils: {
34
+ deepDispose(object: never): void;
35
+ rotateVRM0(vrm: never): void;
36
+ };
37
+ };
38
+ }
@@ -1,4 +1,5 @@
1
- export const runtimeCapabilityVersion = 1 as const;
1
+ /** The only capability version this build provides; any other requested version is refused. */
2
+ export const runtimeCapabilityVersion = 2 as const;
2
3
  export const runtimeCapabilityKey = 'turbowarpAFrameCapability';
3
4
 
4
5
  export interface AFrameScenePort {
@@ -11,26 +12,32 @@ export interface AFrameScenePort {
11
12
  countSelector(selector: string): number;
12
13
  }
13
14
 
14
- export interface AFrameRuntimeCapabilityV1 extends AFrameScenePort {
15
+ export type AFrameVrmState = 'none' | 'loading' | 'ready' | 'error';
16
+
17
+ export interface AFrameVrmStatus {
18
+ state: AFrameVrmState;
19
+ error: string;
20
+ }
21
+
22
+ export interface AFrameVrmPort {
23
+ /** Loads a VRM onto the first node matching the selector; resolves when it is ready. */
24
+ loadVrm(url: string, selector: string): Promise<void>;
25
+ /** Euler degrees on a normalized humanoid bone, relative to the T-pose. */
26
+ setVrmBoneRotation(selector: string, bone: string, x: number, y: number, z: number): void;
27
+ vrmBoneNames(selector: string): string[];
28
+ vrmStatus(selector: string): AFrameVrmStatus;
29
+ }
30
+
31
+ export interface AFrameRuntimeCapabilityV2 extends AFrameScenePort, AFrameVrmPort {
15
32
  readonly version: typeof runtimeCapabilityVersion;
16
- requireVersion(version: number): AFrameRuntimeCapabilityV1;
33
+ requireVersion(version: number): AFrameRuntimeCapabilityV2;
17
34
  }
18
35
 
19
36
  export function createRuntimeCapability(
20
- scene: AFrameScenePort,
37
+ scene: AFrameScenePort & AFrameVrmPort,
21
38
  assertActive: () => void
22
- ): AFrameRuntimeCapabilityV1 {
23
- const capability: AFrameRuntimeCapabilityV1 = {
24
- version: runtimeCapabilityVersion,
25
- requireVersion(version) {
26
- assertActive();
27
- if (version !== runtimeCapabilityVersion) {
28
- throw new Error(
29
- `Unsupported A-Frame runtime capability version: ${version}; supported version is ${runtimeCapabilityVersion}.`
30
- );
31
- }
32
- return capability;
33
- },
39
+ ): AFrameRuntimeCapabilityV2 {
40
+ const scenePort: AFrameScenePort = {
34
41
  loadTemplate(id, source) {
35
42
  assertActive();
36
43
  scene.loadTemplate(id, source);
@@ -60,5 +67,39 @@ export function createRuntimeCapability(
60
67
  return scene.countSelector(selector);
61
68
  }
62
69
  };
63
- return Object.freeze(capability);
70
+
71
+ const vrmPort: AFrameVrmPort = {
72
+ async loadVrm(url, selector) {
73
+ assertActive();
74
+ await scene.loadVrm(url, selector);
75
+ },
76
+ setVrmBoneRotation(selector, bone, x, y, z) {
77
+ assertActive();
78
+ scene.setVrmBoneRotation(selector, bone, x, y, z);
79
+ },
80
+ vrmBoneNames(selector) {
81
+ assertActive();
82
+ return scene.vrmBoneNames(selector);
83
+ },
84
+ vrmStatus(selector) {
85
+ assertActive();
86
+ return scene.vrmStatus(selector);
87
+ }
88
+ };
89
+
90
+ const capability: AFrameRuntimeCapabilityV2 = Object.freeze({
91
+ version: runtimeCapabilityVersion,
92
+ requireVersion(version: number) {
93
+ assertActive();
94
+ if (version !== runtimeCapabilityVersion) {
95
+ throw new Error(
96
+ `Unsupported A-Frame runtime capability version: ${version}; supported version is ${runtimeCapabilityVersion}.`
97
+ );
98
+ }
99
+ return capability;
100
+ },
101
+ ...scenePort,
102
+ ...vrmPort
103
+ });
104
+ return capability;
64
105
  }
package/src/vrm.ts ADDED
@@ -0,0 +1,143 @@
1
+ import {createThreeVrm} from 'virtual:three-vrm-factory';
2
+
3
+ /** The subset of Three.js, as exposed by `AFRAME.THREE`, that VRM avatars use. */
4
+ export interface VrmThreeApi {
5
+ GLTFLoader: new () => GltfLoaderLike;
6
+ MathUtils: {degToRad(degrees: number): number};
7
+ }
8
+
9
+ interface GltfLoaderLike {
10
+ register(callback: (parser: unknown) => unknown): unknown;
11
+ loadAsync(url: string): Promise<{userData: {vrm?: VrmLike}}>;
12
+ }
13
+
14
+ interface BoneLike {
15
+ rotation: {set(x: number, y: number, z: number): unknown};
16
+ }
17
+
18
+ export interface VrmLike {
19
+ scene: object;
20
+ meta?: {metaVersion?: string};
21
+ humanoid: {
22
+ humanBones: Record<string, unknown>;
23
+ getNormalizedBoneNode(name: string): BoneLike | null;
24
+ };
25
+ update(deltaSeconds: number): void;
26
+ }
27
+
28
+ export type VrmState = 'none' | 'loading' | 'ready' | 'error';
29
+
30
+ interface VrmEntry {
31
+ state: VrmState;
32
+ error: string;
33
+ vrm: VrmLike | null;
34
+ generation: number;
35
+ }
36
+
37
+ /**
38
+ * Loads VRM avatars onto A-Frame nodes and turns their humanoid bones.
39
+ *
40
+ * Rotations are written to the normalized humanoid bones, whose rest pose is the same
41
+ * T-pose for every model, and `update` copies them to the model's own bones. That is
42
+ * what makes one rotation mean the same thing on any VRM.
43
+ */
44
+ export class VrmAvatars {
45
+ private readonly entries = new Map<string, VrmEntry>();
46
+ private vrmApi: ReturnType<typeof createThreeVrm> | null = null;
47
+ private vrmApiThree: VrmThreeApi | null = null;
48
+ private generation = 0;
49
+
50
+ public constructor(private readonly getThree: () => VrmThreeApi | null) {}
51
+
52
+ public async load(nodeId: string, url: string, attach: (scene: object) => void): Promise<void> {
53
+ const generation = ++this.generation;
54
+ this.remove(nodeId);
55
+ const entry: VrmEntry = {state: 'loading', error: '', vrm: null, generation};
56
+ this.entries.set(nodeId, entry);
57
+ try {
58
+ const THREE = this.requireThree();
59
+ const {VRMLoaderPlugin, VRMUtils} = this.api(THREE);
60
+ const loader = new THREE.GLTFLoader();
61
+ loader.register((parser) => new VRMLoaderPlugin(parser as never));
62
+ const gltf = await loader.loadAsync(url);
63
+ const vrm = gltf.userData.vrm;
64
+ if (vrm === undefined) throw new Error(`Not a VRM file: ${url}`);
65
+ if (this.entries.get(nodeId)?.generation !== generation) {
66
+ VRMUtils.deepDispose(vrm.scene as never);
67
+ return;
68
+ }
69
+ VRMUtils.rotateVRM0(vrm as never);
70
+ attach(vrm.scene);
71
+ entry.vrm = vrm;
72
+ entry.state = 'ready';
73
+ } catch (error) {
74
+ if (this.entries.get(nodeId)?.generation !== generation) return;
75
+ entry.state = 'error';
76
+ entry.error = error instanceof Error ? error.message : String(error);
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ public setBoneRotation(nodeId: string, bone: string, degrees: {x: number; y: number; z: number}): void {
82
+ const vrm = this.requireVrm(nodeId);
83
+ const node = vrm.humanoid.getNormalizedBoneNode(bone);
84
+ if (node === null) throw new Error(`VRM ${nodeId} has no humanoid bone: ${bone}`);
85
+ const {degToRad} = this.requireThree().MathUtils;
86
+ node.rotation.set(degToRad(degrees.x), degToRad(degrees.y), degToRad(degrees.z));
87
+ }
88
+
89
+ public boneNames(nodeId: string): string[] {
90
+ const vrm = this.entries.get(nodeId)?.vrm;
91
+ if (vrm === null || vrm === undefined) return [];
92
+ return Object.keys(vrm.humanoid.humanBones).filter(
93
+ (name) => vrm.humanoid.getNormalizedBoneNode(name) !== null
94
+ );
95
+ }
96
+
97
+ public state(nodeId: string): VrmState {
98
+ return this.entries.get(nodeId)?.state ?? 'none';
99
+ }
100
+
101
+ public error(nodeId: string): string {
102
+ return this.entries.get(nodeId)?.error ?? '';
103
+ }
104
+
105
+ public update(deltaSeconds: number): void {
106
+ for (const entry of this.entries.values()) entry.vrm?.update(deltaSeconds);
107
+ }
108
+
109
+ public remove(nodeId: string): void {
110
+ const entry = this.entries.get(nodeId);
111
+ if (entry === undefined) return;
112
+ this.entries.delete(nodeId);
113
+ if (entry.vrm !== null && this.vrmApi !== null) {
114
+ this.vrmApi.VRMUtils.deepDispose(entry.vrm.scene as never);
115
+ }
116
+ }
117
+
118
+ public clear(): void {
119
+ for (const nodeId of [...this.entries.keys()]) this.remove(nodeId);
120
+ }
121
+
122
+ private requireVrm(nodeId: string): VrmLike {
123
+ const entry = this.entries.get(nodeId);
124
+ if (entry?.vrm === null || entry?.vrm === undefined) {
125
+ throw new Error(`VRM ${nodeId} is ${entry?.state ?? 'not loaded'}.`);
126
+ }
127
+ return entry.vrm;
128
+ }
129
+
130
+ private requireThree(): VrmThreeApi {
131
+ const THREE = this.getThree();
132
+ if (THREE === null) throw new Error('VRM avatars need A-Frame to be loaded first.');
133
+ return THREE;
134
+ }
135
+
136
+ private api(THREE: VrmThreeApi): ReturnType<typeof createThreeVrm> {
137
+ if (this.vrmApi === null || this.vrmApiThree !== THREE) {
138
+ this.vrmApi = createThreeVrm(THREE);
139
+ this.vrmApiThree = THREE;
140
+ }
141
+ return this.vrmApi;
142
+ }
143
+ }