@kubohiroya/turbowarp-aframe 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +18 -8
- package/README.md +86 -9
- package/THIRD_PARTY_NOTICES.md +17 -0
- package/dist/extension-manifest.json +88 -0
- package/dist/turbowarp-aframe.js +6469 -44
- package/docs/architecture.ja.md +5 -3
- package/docs/architecture.md +5 -3
- package/package.json +6 -2
- package/src/aframe-loader.ts +74 -0
- package/src/block-definitions.json +62 -1
- package/src/extension.ts +101 -6
- package/src/globals.d.ts +10 -0
- package/src/runtime-capability.ts +69 -17
- package/src/vrm.ts +168 -0
package/docs/architecture.ja.md
CHANGED
|
@@ -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
|
|
27
|
+
機能拡張は`Scratch.vm.runtime.turbowarpAFrameCapability`を公開します。version 2は、`loadTemplate`、`createFromTemplate`、`setPosition`、`setRotation`、`emitEvent`、`deleteSelector`、`countSelector`に、`loadVrm`、`setVrmBoneRotation`、`vrmBoneNames`、`vrmStatus`、`setVrmExpression`、`vrmExpressionNames`を加えた、freezeされた狭い型付きportです。scene操作だけを持っていたversion 1は、version 2と並べて残さず0.4.0で撤去しました。正しく保つ契約を1つにするためです。表情の操作は、methodを加えるだけでconsumerは使うmethodの有無を確かめるため、versionを変えずにversion 2へ加えました。
|
|
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
|
|
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
|
|
package/docs/architecture.md
CHANGED
|
@@ -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
|
|
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`, `vrmStatus`, `setVrmExpression`, and `vrmExpressionNames`. The expression operations were added to version 2 without changing its version, because they only add methods and a consumer checks for the methods it uses. 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(
|
|
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
|
+
"version": "0.5.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": "
|
|
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,67 @@
|
|
|
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": "setVrmExpression",
|
|
362
|
+
"blockType": "COMMAND",
|
|
363
|
+
"text": "set VRM [SELECTOR] expression [NAME] to [WEIGHT]",
|
|
364
|
+
"description": "Sets the weight, clamped to 0 through 1, of a preset or custom VRM expression such as happy or blink on every matching node whose VRM is ready.",
|
|
365
|
+
"arguments": {
|
|
366
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"},
|
|
367
|
+
"NAME": {"type": "STRING", "defaultValue": "happy"},
|
|
368
|
+
"WEIGHT": {"type": "NUMBER", "defaultValue": 1}
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
{
|
|
372
|
+
"opcode": "vrmExpressionNames",
|
|
373
|
+
"blockType": "REPORTER",
|
|
374
|
+
"text": "VRM [SELECTOR] expressions",
|
|
375
|
+
"description": "Returns the preset and custom expression names of the first matching node's VRM as a JSON array.",
|
|
376
|
+
"arguments": {
|
|
377
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
{
|
|
381
|
+
"opcode": "vrmState",
|
|
382
|
+
"blockType": "REPORTER",
|
|
383
|
+
"text": "VRM [SELECTOR] state",
|
|
384
|
+
"description": "Returns none, loading, ready, or error with its reason for the first matching node.",
|
|
385
|
+
"arguments": {
|
|
386
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
|
|
387
|
+
}
|
|
327
388
|
}
|
|
328
389
|
]
|
|
329
390
|
}
|
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
|
|
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:
|
|
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,15 @@ 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)),
|
|
170
|
+
setVrmExpression: (selector, name, weight) =>
|
|
171
|
+
this.setVrmExpression({SELECTOR: selector, NAME: name, WEIGHT: weight}),
|
|
172
|
+
vrmExpressionNames: (selector) => this.vrmExpressionNamesFor(Scratch.Cast.toString(selector))
|
|
156
173
|
},
|
|
157
174
|
() => this.assertActive()
|
|
158
175
|
);
|
|
@@ -170,7 +187,8 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
170
187
|
};
|
|
171
188
|
}
|
|
172
189
|
|
|
173
|
-
public createScene(args: {LAYER: unknown; MODE: unknown}): void {
|
|
190
|
+
public async createScene(args: {LAYER: unknown; MODE: unknown}): Promise<void> {
|
|
191
|
+
await ensureAFrame();
|
|
174
192
|
this.sceneOptions = {
|
|
175
193
|
layer: Scratch.Cast.toString(args.LAYER) || 'above-stage',
|
|
176
194
|
mode: Scratch.Cast.toString(args.MODE) || '3d'
|
|
@@ -500,8 +518,61 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
500
518
|
});
|
|
501
519
|
}
|
|
502
520
|
|
|
521
|
+
public async loadVrm(args: {URL: unknown; SELECTOR: unknown}): Promise<void> {
|
|
522
|
+
const selector = Scratch.Cast.toString(args.SELECTOR);
|
|
523
|
+
const node = this.firstMatch(selector);
|
|
524
|
+
if (node === undefined) throw new Error(`No A-Frame node matches: ${selector}`);
|
|
525
|
+
const element = node.element as (Element & VrmHostElement) | null;
|
|
526
|
+
if (element === null) throw new Error('VRM avatars need a scene in the browser.');
|
|
527
|
+
this.ensureAnimationTickBridge();
|
|
528
|
+
await this.vrms.load(node.id, Scratch.Cast.toString(args.URL), (scene) => {
|
|
529
|
+
if (element.setObject3D !== undefined) {
|
|
530
|
+
element.setObject3D('vrm', scene);
|
|
531
|
+
} else {
|
|
532
|
+
element.object3D?.add(scene);
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
public setVrmBoneRotation(args: {
|
|
538
|
+
SELECTOR: unknown;
|
|
539
|
+
BONE: unknown;
|
|
540
|
+
X: unknown;
|
|
541
|
+
Y: unknown;
|
|
542
|
+
Z: unknown;
|
|
543
|
+
}): void {
|
|
544
|
+
const bone = Scratch.Cast.toString(args.BONE).trim();
|
|
545
|
+
const rotation = this.argsToVec3(args);
|
|
546
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
547
|
+
if (this.vrms.state(node.id) !== 'ready') continue;
|
|
548
|
+
this.vrms.setBoneRotation(node.id, bone, rotation);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
public setVrmExpression(args: {SELECTOR: unknown; NAME: unknown; WEIGHT: unknown}): void {
|
|
553
|
+
const name = Scratch.Cast.toString(args.NAME).trim();
|
|
554
|
+
const weight = Scratch.Cast.toNumber(args.WEIGHT);
|
|
555
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
556
|
+
if (this.vrms.state(node.id) !== 'ready') continue;
|
|
557
|
+
this.vrms.setExpression(node.id, name, weight);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
public vrmExpressionNames(args: {SELECTOR: unknown}): string {
|
|
562
|
+
return JSON.stringify(this.vrmExpressionNamesFor(Scratch.Cast.toString(args.SELECTOR)));
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
public vrmBoneNames(args: {SELECTOR: unknown}): string {
|
|
566
|
+
return JSON.stringify(this.vrmBoneNamesFor(Scratch.Cast.toString(args.SELECTOR)));
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
public vrmState(args: {SELECTOR: unknown}): string {
|
|
570
|
+
const {state, error} = this.vrmStatusFor(Scratch.Cast.toString(args.SELECTOR));
|
|
571
|
+
return state === 'error' ? `error: ${error}` : state;
|
|
572
|
+
}
|
|
573
|
+
|
|
503
574
|
public testStepAnimations(args: {DELTA: unknown}): void {
|
|
504
|
-
this.
|
|
575
|
+
this.updateFrame(Scratch.Cast.toNumber(args.DELTA) / 1000);
|
|
505
576
|
}
|
|
506
577
|
|
|
507
578
|
public snapshot(): Record<string, unknown> {
|
|
@@ -545,6 +616,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
545
616
|
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
546
617
|
this.stopPlayback(key, true);
|
|
547
618
|
}
|
|
619
|
+
this.vrms.clear();
|
|
548
620
|
this.rootElement?.parentElement?.remove();
|
|
549
621
|
this.rootElement = null;
|
|
550
622
|
const runtime = Scratch.vm?.runtime;
|
|
@@ -563,6 +635,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
563
635
|
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
564
636
|
this.stopPlayback(key, true);
|
|
565
637
|
}
|
|
638
|
+
this.vrms.clear();
|
|
566
639
|
this.nodes.clear();
|
|
567
640
|
this.nodes.set(ROOT_ID, {
|
|
568
641
|
id: ROOT_ID,
|
|
@@ -627,6 +700,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
627
700
|
}
|
|
628
701
|
node.element?.remove();
|
|
629
702
|
this.nodes.delete(id);
|
|
703
|
+
this.vrms.remove(id);
|
|
630
704
|
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
631
705
|
if (key.startsWith(`${id}:`)) {
|
|
632
706
|
this.stopPlayback(key, true);
|
|
@@ -1034,6 +1108,27 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
1034
1108
|
}
|
|
1035
1109
|
}
|
|
1036
1110
|
|
|
1111
|
+
private vrmBoneNamesFor(selector: string): string[] {
|
|
1112
|
+
const node = this.firstMatch(selector);
|
|
1113
|
+
return node === undefined ? [] : this.vrms.boneNames(node.id);
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
private vrmExpressionNamesFor(selector: string): string[] {
|
|
1117
|
+
const node = this.firstMatch(selector);
|
|
1118
|
+
return node === undefined ? [] : this.vrms.expressionNames(node.id);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
private vrmStatusFor(selector: string): AFrameVrmStatus {
|
|
1122
|
+
const node = this.firstMatch(selector);
|
|
1123
|
+
if (node === undefined) return {state: 'none', error: ''};
|
|
1124
|
+
return {state: this.vrms.state(node.id), error: this.vrms.error(node.id)};
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
private updateFrame(deltaTime: number): void {
|
|
1128
|
+
this.updateAnimationMixers(deltaTime);
|
|
1129
|
+
if (Number.isFinite(deltaTime) && deltaTime >= 0) this.vrms.update(deltaTime);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1037
1132
|
private updateAnimationMixers(deltaTime: number): void {
|
|
1038
1133
|
if (!Number.isFinite(deltaTime) || deltaTime < 0) return;
|
|
1039
1134
|
for (const playback of this.animationPlaybacks.values()) {
|
|
@@ -1054,7 +1149,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
1054
1149
|
schema: {id: {type: 'string'}},
|
|
1055
1150
|
tick(this: {data: {id: string}}, _time: number, timeDelta: number) {
|
|
1056
1151
|
const extension = animationRuntimeRegistry().get(this.data.id);
|
|
1057
|
-
extension?.
|
|
1152
|
+
extension?.updateFrame(timeDelta / 1000);
|
|
1058
1153
|
}
|
|
1059
1154
|
});
|
|
1060
1155
|
}
|
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
|
-
|
|
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,35 @@ export interface AFrameScenePort {
|
|
|
11
12
|
countSelector(selector: string): number;
|
|
12
13
|
}
|
|
13
14
|
|
|
14
|
-
export
|
|
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
|
+
/** Weight from 0 through 1, clamped, of a preset or custom VRM expression. */
|
|
30
|
+
setVrmExpression(selector: string, name: string, weight: number): void;
|
|
31
|
+
vrmExpressionNames(selector: string): string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface AFrameRuntimeCapabilityV2 extends AFrameScenePort, AFrameVrmPort {
|
|
15
35
|
readonly version: typeof runtimeCapabilityVersion;
|
|
16
|
-
requireVersion(version: number):
|
|
36
|
+
requireVersion(version: number): AFrameRuntimeCapabilityV2;
|
|
17
37
|
}
|
|
18
38
|
|
|
19
39
|
export function createRuntimeCapability(
|
|
20
|
-
scene: AFrameScenePort,
|
|
40
|
+
scene: AFrameScenePort & AFrameVrmPort,
|
|
21
41
|
assertActive: () => void
|
|
22
|
-
):
|
|
23
|
-
const
|
|
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
|
-
},
|
|
42
|
+
): AFrameRuntimeCapabilityV2 {
|
|
43
|
+
const scenePort: AFrameScenePort = {
|
|
34
44
|
loadTemplate(id, source) {
|
|
35
45
|
assertActive();
|
|
36
46
|
scene.loadTemplate(id, source);
|
|
@@ -60,5 +70,47 @@ export function createRuntimeCapability(
|
|
|
60
70
|
return scene.countSelector(selector);
|
|
61
71
|
}
|
|
62
72
|
};
|
|
63
|
-
|
|
73
|
+
|
|
74
|
+
const vrmPort: AFrameVrmPort = {
|
|
75
|
+
async loadVrm(url, selector) {
|
|
76
|
+
assertActive();
|
|
77
|
+
await scene.loadVrm(url, selector);
|
|
78
|
+
},
|
|
79
|
+
setVrmBoneRotation(selector, bone, x, y, z) {
|
|
80
|
+
assertActive();
|
|
81
|
+
scene.setVrmBoneRotation(selector, bone, x, y, z);
|
|
82
|
+
},
|
|
83
|
+
vrmBoneNames(selector) {
|
|
84
|
+
assertActive();
|
|
85
|
+
return scene.vrmBoneNames(selector);
|
|
86
|
+
},
|
|
87
|
+
vrmStatus(selector) {
|
|
88
|
+
assertActive();
|
|
89
|
+
return scene.vrmStatus(selector);
|
|
90
|
+
},
|
|
91
|
+
setVrmExpression(selector, name, weight) {
|
|
92
|
+
assertActive();
|
|
93
|
+
scene.setVrmExpression(selector, name, weight);
|
|
94
|
+
},
|
|
95
|
+
vrmExpressionNames(selector) {
|
|
96
|
+
assertActive();
|
|
97
|
+
return scene.vrmExpressionNames(selector);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const capability: AFrameRuntimeCapabilityV2 = Object.freeze({
|
|
102
|
+
version: runtimeCapabilityVersion,
|
|
103
|
+
requireVersion(version: number) {
|
|
104
|
+
assertActive();
|
|
105
|
+
if (version !== runtimeCapabilityVersion) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`Unsupported A-Frame runtime capability version: ${version}; supported version is ${runtimeCapabilityVersion}.`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return capability;
|
|
111
|
+
},
|
|
112
|
+
...scenePort,
|
|
113
|
+
...vrmPort
|
|
114
|
+
});
|
|
115
|
+
return capability;
|
|
64
116
|
}
|