@kubohiroya/turbowarp-aframe 0.2.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/LICENSE +373 -0
- package/README.ja.md +131 -0
- package/README.md +462 -0
- package/dist/extension-manifest.json +517 -0
- package/dist/turbowarp-aframe.js +1422 -0
- package/docs/architecture.ja.md +136 -0
- package/docs/architecture.md +136 -0
- package/docs/index.html +50 -0
- package/package.json +66 -0
- package/schemas/aframe-template.schema.json +40 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/block-definitions.json +329 -0
- package/src/config.ts +12 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +1226 -0
- package/src/globals.d.ts +25 -0
- package/src/index.ts +8 -0
package/src/extension.ts
ADDED
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
import {extensionConfig} from './config';
|
|
2
|
+
import definitions from './block-definitions.json';
|
|
3
|
+
|
|
4
|
+
type BlockTypeName = 'COMMAND' | 'REPORTER' | 'HAT' | 'BOOLEAN';
|
|
5
|
+
type ArgumentTypeName = 'STRING' | 'NUMBER' | 'BOOLEAN';
|
|
6
|
+
type Vec3 = {x: number; y: number; z: number};
|
|
7
|
+
|
|
8
|
+
interface DefinitionArgument {
|
|
9
|
+
type: ArgumentTypeName;
|
|
10
|
+
defaultValue?: string | number | boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface BlockDefinition {
|
|
14
|
+
opcode: string;
|
|
15
|
+
blockType: BlockTypeName;
|
|
16
|
+
text: string;
|
|
17
|
+
description: string;
|
|
18
|
+
arguments: Record<string, DefinitionArgument>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface TemplateNode {
|
|
22
|
+
type?: string;
|
|
23
|
+
id?: string;
|
|
24
|
+
class?: string | string[];
|
|
25
|
+
classes?: string[];
|
|
26
|
+
data?: Record<string, unknown>;
|
|
27
|
+
attributes?: Record<string, unknown>;
|
|
28
|
+
children?: TemplateNode[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface SceneNode {
|
|
32
|
+
id: string;
|
|
33
|
+
type: string;
|
|
34
|
+
parentId: string | null;
|
|
35
|
+
children: string[];
|
|
36
|
+
classes: Set<string>;
|
|
37
|
+
data: Map<string, string>;
|
|
38
|
+
attributes: Map<string, string>;
|
|
39
|
+
element: Element | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface SceneEvent {
|
|
43
|
+
type: string;
|
|
44
|
+
targetId: string;
|
|
45
|
+
data: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface SceneOptions {
|
|
49
|
+
layer: string;
|
|
50
|
+
mode: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type KeyframeTrackType = 'vector' | 'quaternion';
|
|
54
|
+
|
|
55
|
+
interface KeyframeTrackDefinition {
|
|
56
|
+
type: KeyframeTrackType;
|
|
57
|
+
path: string;
|
|
58
|
+
times: number[];
|
|
59
|
+
values: number[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface AnimationClipDefinition {
|
|
63
|
+
name: string;
|
|
64
|
+
duration: number;
|
|
65
|
+
tracks: KeyframeTrackDefinition[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface AnimationPlayback {
|
|
69
|
+
nodeId: string;
|
|
70
|
+
clipName: string;
|
|
71
|
+
loop: boolean;
|
|
72
|
+
active: boolean;
|
|
73
|
+
paused: boolean;
|
|
74
|
+
timeScale: number;
|
|
75
|
+
mixer: AnimationMixerLike | null;
|
|
76
|
+
action: AnimationActionLike | null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface AnimationActionLike {
|
|
80
|
+
paused?: boolean;
|
|
81
|
+
timeScale?: number;
|
|
82
|
+
setLoop?(mode: unknown, repetitions: number): AnimationActionLike;
|
|
83
|
+
play?(): AnimationActionLike;
|
|
84
|
+
stop?(): AnimationActionLike;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface AnimationMixerLike {
|
|
88
|
+
clipAction(clip: unknown): AnimationActionLike;
|
|
89
|
+
update(deltaTime: number): void;
|
|
90
|
+
stopAllAction?(): void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface ThreeAnimationApi {
|
|
94
|
+
AnimationClip: new (name: string, duration: number, tracks: unknown[]) => unknown;
|
|
95
|
+
AnimationMixer: new (root: unknown) => AnimationMixerLike;
|
|
96
|
+
LoopOnce?: unknown;
|
|
97
|
+
LoopRepeat?: unknown;
|
|
98
|
+
QuaternionKeyframeTrack: new (name: string, times: number[], values: number[]) => unknown;
|
|
99
|
+
VectorKeyframeTrack: new (name: string, times: number[], values: number[]) => unknown;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
type AFrameApi = {
|
|
103
|
+
THREE?: ThreeAnimationApi;
|
|
104
|
+
components?: Record<string, unknown>;
|
|
105
|
+
registerComponent(name: string, definition: unknown): void;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
|
|
109
|
+
const ROOT_ID = 'scene';
|
|
110
|
+
const DOM_EVENT_TYPES = ['click', 'tap', 'pointerenter', 'pointerleave'] as const;
|
|
111
|
+
const TEMPLATE_NODE_KEYS = new Set([
|
|
112
|
+
'attributes',
|
|
113
|
+
'children',
|
|
114
|
+
'class',
|
|
115
|
+
'classes',
|
|
116
|
+
'data',
|
|
117
|
+
'id',
|
|
118
|
+
'type'
|
|
119
|
+
]);
|
|
120
|
+
|
|
121
|
+
export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
122
|
+
private readonly nodes = new Map<string, SceneNode>();
|
|
123
|
+
private readonly templates = new Map<string, TemplateNode>();
|
|
124
|
+
private readonly animationClips = new Map<string, AnimationClipDefinition>();
|
|
125
|
+
private readonly animationPlaybacks = new Map<string, AnimationPlayback>();
|
|
126
|
+
private readonly eventQueue: SceneEvent[] = [];
|
|
127
|
+
private readonly domEventTypes = new Set<string>(DOM_EVENT_TYPES);
|
|
128
|
+
private readonly runtimeId = `twaframe-${Math.random().toString(36).slice(2)}`;
|
|
129
|
+
private sceneOptions: SceneOptions = {layer: 'above-stage', mode: '3d'};
|
|
130
|
+
private rootElement: Element | null = null;
|
|
131
|
+
private sceneReadyPending = false;
|
|
132
|
+
private lastEvent: SceneEvent | null = null;
|
|
133
|
+
|
|
134
|
+
public constructor() {
|
|
135
|
+
this.resetGraph();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
public getInfo(): Record<string, unknown> {
|
|
139
|
+
return {
|
|
140
|
+
id: extensionConfig.id,
|
|
141
|
+
name: Scratch.translate(definitions.extensionName),
|
|
142
|
+
docsURI: extensionConfig.docsURI,
|
|
143
|
+
blockIconURI: extensionConfig.blockIconURI,
|
|
144
|
+
blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
public createScene(args: {LAYER: unknown; MODE: unknown}): void {
|
|
149
|
+
this.sceneOptions = {
|
|
150
|
+
layer: Scratch.Cast.toString(args.LAYER) || 'above-stage',
|
|
151
|
+
mode: Scratch.Cast.toString(args.MODE) || '3d'
|
|
152
|
+
};
|
|
153
|
+
this.resetGraph();
|
|
154
|
+
this.rootElement = this.createSceneElement();
|
|
155
|
+
const root = this.requireNode(ROOT_ID);
|
|
156
|
+
root.element = this.rootElement;
|
|
157
|
+
this.applyNodeToElement(root);
|
|
158
|
+
this.sceneReadyPending = true;
|
|
159
|
+
this.enqueueEvent({type: 'scene-ready', targetId: ROOT_ID, data: '{}'});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
public loadTemplate(args: {ID: unknown; SOURCE: unknown}): void {
|
|
163
|
+
const id = this.normalizeId(Scratch.Cast.toString(args.ID));
|
|
164
|
+
const template = this.parseTemplate(Scratch.Cast.toString(args.SOURCE));
|
|
165
|
+
this.templates.set(id, template);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public createNode(args: {TYPE: unknown; ID: unknown; PARENT: unknown}): void {
|
|
169
|
+
const parent = this.firstMatch(Scratch.Cast.toString(args.PARENT)) ?? this.requireNode(ROOT_ID);
|
|
170
|
+
this.addNode(
|
|
171
|
+
{
|
|
172
|
+
type: Scratch.Cast.toString(args.TYPE),
|
|
173
|
+
id: Scratch.Cast.toString(args.ID)
|
|
174
|
+
},
|
|
175
|
+
parent.id
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public createFromTemplate(args: {TEMPLATE: unknown; INSTANCE: unknown; PARENT: unknown}): void {
|
|
180
|
+
const templateId = this.normalizeId(Scratch.Cast.toString(args.TEMPLATE));
|
|
181
|
+
const instanceId = this.normalizeId(Scratch.Cast.toString(args.INSTANCE));
|
|
182
|
+
const template = this.templates.get(templateId);
|
|
183
|
+
if (template === undefined) {
|
|
184
|
+
throw new Error(`Unknown A-Frame template: ${templateId}`);
|
|
185
|
+
}
|
|
186
|
+
const parent = this.firstMatch(Scratch.Cast.toString(args.PARENT)) ?? this.requireNode(ROOT_ID);
|
|
187
|
+
const rootTemplate: TemplateNode = {
|
|
188
|
+
...template,
|
|
189
|
+
id: instanceId,
|
|
190
|
+
data: {...template.data, template: templateId, instance: instanceId}
|
|
191
|
+
};
|
|
192
|
+
this.addNodeTree(rootTemplate, parent.id, instanceId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
public setPosition(args: {SELECTOR: unknown; X: unknown; Y: unknown; Z: unknown}): void {
|
|
196
|
+
this.setVec3Attribute(Scratch.Cast.toString(args.SELECTOR), 'position', this.argsToVec3(args));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
public moveBy(args: {SELECTOR: unknown; X: unknown; Y: unknown; Z: unknown}): void {
|
|
200
|
+
const delta = this.argsToVec3(args);
|
|
201
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
202
|
+
const current = this.parseVec3(node.attributes.get('position'));
|
|
203
|
+
this.setVec3(node, 'position', {
|
|
204
|
+
x: current.x + delta.x,
|
|
205
|
+
y: current.y + delta.y,
|
|
206
|
+
z: current.z + delta.z
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
public setRotation(args: {SELECTOR: unknown; X: unknown; Y: unknown; Z: unknown}): void {
|
|
212
|
+
this.setVec3Attribute(Scratch.Cast.toString(args.SELECTOR), 'rotation', this.argsToVec3(args));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
public addClass(args: {CLASS: unknown; SELECTOR: unknown}): void {
|
|
216
|
+
const className = this.normalizeToken(Scratch.Cast.toString(args.CLASS));
|
|
217
|
+
if (className.length === 0) return;
|
|
218
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
219
|
+
node.classes.add(className);
|
|
220
|
+
this.applyNodeToElement(node);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
public setData(args: {SELECTOR: unknown; KEY: unknown; VALUE: unknown}): void {
|
|
225
|
+
const key = this.normalizeDataKey(Scratch.Cast.toString(args.KEY));
|
|
226
|
+
const value = Scratch.Cast.toString(args.VALUE);
|
|
227
|
+
if (key.length === 0) return;
|
|
228
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
229
|
+
node.data.set(key, value);
|
|
230
|
+
this.applyNodeToElement(node);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
public setAttribute(args: {SELECTOR: unknown; NAME: unknown; VALUE: unknown}): void {
|
|
235
|
+
const name = this.normalizeAttributeName(Scratch.Cast.toString(args.NAME));
|
|
236
|
+
const value = Scratch.Cast.toString(args.VALUE);
|
|
237
|
+
if (name.length === 0) return;
|
|
238
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
239
|
+
node.attributes.set(name, value);
|
|
240
|
+
this.applyNodeToElement(node);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
public deleteSelector(args: {SELECTOR: unknown}): void {
|
|
245
|
+
const targets = this.matches(Scratch.Cast.toString(args.SELECTOR)).filter(
|
|
246
|
+
(node) => node.id !== ROOT_ID
|
|
247
|
+
);
|
|
248
|
+
for (const node of targets) {
|
|
249
|
+
if (this.nodes.has(node.id)) {
|
|
250
|
+
this.deleteNode(node.id);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
public countSelector(args: {SELECTOR: unknown}): number {
|
|
256
|
+
return this.matches(Scratch.Cast.toString(args.SELECTOR)).length;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
public eventTargetId(): string {
|
|
260
|
+
return this.lastEvent?.targetId ?? '';
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
public emitEvent(args: {TYPE: unknown; SELECTOR: unknown; DATA: unknown}): void {
|
|
264
|
+
const target = this.firstMatch(Scratch.Cast.toString(args.SELECTOR));
|
|
265
|
+
if (target === undefined) return;
|
|
266
|
+
this.enqueueEvent({
|
|
267
|
+
type: Scratch.Cast.toString(args.TYPE),
|
|
268
|
+
targetId: target.id,
|
|
269
|
+
data: Scratch.Cast.toString(args.DATA)
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
public whenSceneReady(): boolean {
|
|
274
|
+
if (!this.sceneReadyPending) return false;
|
|
275
|
+
this.sceneReadyPending = false;
|
|
276
|
+
this.lastEvent = {type: 'scene-ready', targetId: ROOT_ID, data: '{}'};
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
public whenEventOnSelector(args: {TYPE: unknown; SELECTOR: unknown}): boolean {
|
|
281
|
+
const type = Scratch.Cast.toString(args.TYPE);
|
|
282
|
+
const selector = Scratch.Cast.toString(args.SELECTOR);
|
|
283
|
+
this.domEventTypes.add(type);
|
|
284
|
+
this.attachDomEventType(type);
|
|
285
|
+
const index = this.eventQueue.findIndex((event) => {
|
|
286
|
+
if (event.type !== type) return false;
|
|
287
|
+
const target = this.nodes.get(event.targetId);
|
|
288
|
+
return target !== undefined && this.matchesSelector(target, selector);
|
|
289
|
+
});
|
|
290
|
+
if (index < 0) return false;
|
|
291
|
+
const [event] = this.eventQueue.splice(index, 1);
|
|
292
|
+
this.lastEvent = event ?? null;
|
|
293
|
+
return event !== undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
public createAnimationClip(args: {NAME: unknown; DURATION: unknown}): void {
|
|
297
|
+
const name = this.normalizeId(Scratch.Cast.toString(args.NAME));
|
|
298
|
+
const duration = Scratch.Cast.toNumber(args.DURATION);
|
|
299
|
+
if (!Number.isFinite(duration) || duration < -1) {
|
|
300
|
+
throw new TypeError('Animation clip duration must be -1 or a non-negative number.');
|
|
301
|
+
}
|
|
302
|
+
this.stopClipEverywhere(name);
|
|
303
|
+
this.animationClips.set(name, {
|
|
304
|
+
name,
|
|
305
|
+
duration,
|
|
306
|
+
tracks: []
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
public deleteAnimationClip(args: {NAME: unknown}): void {
|
|
311
|
+
const name = this.normalizeId(Scratch.Cast.toString(args.NAME));
|
|
312
|
+
this.stopClipEverywhere(name);
|
|
313
|
+
this.animationClips.delete(name);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
public addVectorKeyframeTrack(args: {
|
|
317
|
+
CLIP: unknown;
|
|
318
|
+
PATH: unknown;
|
|
319
|
+
TIMES: unknown;
|
|
320
|
+
VALUES: unknown;
|
|
321
|
+
}): void {
|
|
322
|
+
this.addKeyframeTrack(args, 'vector');
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
public addQuaternionKeyframeTrack(args: {
|
|
326
|
+
CLIP: unknown;
|
|
327
|
+
PATH: unknown;
|
|
328
|
+
TIMES: unknown;
|
|
329
|
+
VALUES: unknown;
|
|
330
|
+
}): void {
|
|
331
|
+
this.addKeyframeTrack(args, 'quaternion');
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
public addEulerRotationKeyframeTrack(args: {
|
|
335
|
+
CLIP: unknown;
|
|
336
|
+
PATH: unknown;
|
|
337
|
+
TIMES: unknown;
|
|
338
|
+
VALUES: unknown;
|
|
339
|
+
UNIT: unknown;
|
|
340
|
+
}): void {
|
|
341
|
+
const times = this.parseNumberList(Scratch.Cast.toString(args.TIMES), 'times');
|
|
342
|
+
const eulerValues = this.parseNumberList(Scratch.Cast.toString(args.VALUES), 'values');
|
|
343
|
+
this.validateTrackNumbers(times, eulerValues, 3);
|
|
344
|
+
const unit = this.normalizeEulerUnit(Scratch.Cast.toString(args.UNIT));
|
|
345
|
+
const values: number[] = [];
|
|
346
|
+
for (let index = 0; index < eulerValues.length; index += 3) {
|
|
347
|
+
values.push(
|
|
348
|
+
...this.eulerToQuaternion(
|
|
349
|
+
eulerValues[index] ?? 0,
|
|
350
|
+
eulerValues[index + 1] ?? 0,
|
|
351
|
+
eulerValues[index + 2] ?? 0,
|
|
352
|
+
unit
|
|
353
|
+
)
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
this.pushKeyframeTrack({
|
|
357
|
+
clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
|
|
358
|
+
path: Scratch.Cast.toString(args.PATH),
|
|
359
|
+
trackType: 'quaternion',
|
|
360
|
+
times,
|
|
361
|
+
values
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
public addPositionKeyframe(args: {
|
|
366
|
+
CLIP: unknown;
|
|
367
|
+
TIME: unknown;
|
|
368
|
+
X: unknown;
|
|
369
|
+
Y: unknown;
|
|
370
|
+
Z: unknown;
|
|
371
|
+
}): void {
|
|
372
|
+
this.insertVectorKeyframe(args, '.position');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
public addScaleKeyframe(args: {
|
|
376
|
+
CLIP: unknown;
|
|
377
|
+
TIME: unknown;
|
|
378
|
+
X: unknown;
|
|
379
|
+
Y: unknown;
|
|
380
|
+
Z: unknown;
|
|
381
|
+
}): void {
|
|
382
|
+
this.insertVectorKeyframe(args, '.scale');
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
public addEulerRotationKeyframe(args: {
|
|
386
|
+
CLIP: unknown;
|
|
387
|
+
TIME: unknown;
|
|
388
|
+
X: unknown;
|
|
389
|
+
Y: unknown;
|
|
390
|
+
Z: unknown;
|
|
391
|
+
UNIT: unknown;
|
|
392
|
+
}): void {
|
|
393
|
+
const unit = this.normalizeEulerUnit(Scratch.Cast.toString(args.UNIT));
|
|
394
|
+
this.insertKeyframe({
|
|
395
|
+
clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
|
|
396
|
+
path: '.quaternion',
|
|
397
|
+
trackType: 'quaternion',
|
|
398
|
+
time: Scratch.Cast.toNumber(args.TIME),
|
|
399
|
+
values: this.eulerToQuaternion(
|
|
400
|
+
Scratch.Cast.toNumber(args.X),
|
|
401
|
+
Scratch.Cast.toNumber(args.Y),
|
|
402
|
+
Scratch.Cast.toNumber(args.Z),
|
|
403
|
+
unit
|
|
404
|
+
)
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
public playAnimationClip(args: {CLIP: unknown; SELECTOR: unknown; LOOP: unknown}): void {
|
|
409
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
410
|
+
const clip = this.requireAnimationClip(clipName);
|
|
411
|
+
if (clip.tracks.length === 0) {
|
|
412
|
+
throw new Error(`3D animation clip has no keyframe tracks: ${clipName}`);
|
|
413
|
+
}
|
|
414
|
+
const loop = Scratch.Cast.toBoolean(args.LOOP);
|
|
415
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
416
|
+
const playback = this.createPlayback(node, clip, loop);
|
|
417
|
+
this.animationPlaybacks.set(this.playbackKey(node.id, clipName), playback);
|
|
418
|
+
}
|
|
419
|
+
this.ensureAnimationTickBridge();
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
public stopAnimationClip(args: {CLIP: unknown; SELECTOR: unknown}): void {
|
|
423
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
424
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
425
|
+
this.stopPlayback(this.playbackKey(node.id, clipName), true);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
public pauseAnimationClip(args: {CLIP: unknown; SELECTOR: unknown}): void {
|
|
430
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
431
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
432
|
+
const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
|
|
433
|
+
if (playback === undefined) continue;
|
|
434
|
+
playback.paused = true;
|
|
435
|
+
if (playback.action !== null) {
|
|
436
|
+
playback.action.paused = true;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
public resumeAnimationClip(args: {CLIP: unknown; SELECTOR: unknown}): void {
|
|
442
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
443
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
444
|
+
const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
|
|
445
|
+
if (playback === undefined || !playback.active) continue;
|
|
446
|
+
playback.paused = false;
|
|
447
|
+
if (playback.action !== null) {
|
|
448
|
+
playback.action.paused = false;
|
|
449
|
+
playback.action.play?.();
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
public setAnimationTimeScale(args: {CLIP: unknown; SELECTOR: unknown; SCALE: unknown}): void {
|
|
455
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
456
|
+
const scale = Scratch.Cast.toNumber(args.SCALE);
|
|
457
|
+
if (!Number.isFinite(scale)) {
|
|
458
|
+
throw new TypeError('Animation time scale must be a finite number.');
|
|
459
|
+
}
|
|
460
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
461
|
+
const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
|
|
462
|
+
if (playback === undefined) continue;
|
|
463
|
+
playback.timeScale = scale;
|
|
464
|
+
if (playback.action !== null) {
|
|
465
|
+
playback.action.timeScale = scale;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
public isAnimationClipPlaying(args: {CLIP: unknown; SELECTOR: unknown}): boolean {
|
|
471
|
+
const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
|
|
472
|
+
return this.matches(Scratch.Cast.toString(args.SELECTOR)).some((node) => {
|
|
473
|
+
const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
|
|
474
|
+
return playback?.active === true && playback.paused === false;
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
public testStepAnimations(args: {DELTA: unknown}): void {
|
|
479
|
+
this.updateAnimationMixers(Scratch.Cast.toNumber(args.DELTA) / 1000);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
public snapshot(): Record<string, unknown> {
|
|
483
|
+
return {
|
|
484
|
+
options: this.sceneOptions,
|
|
485
|
+
animationClips: [...this.animationClips.values()].map((clip) => ({
|
|
486
|
+
name: clip.name,
|
|
487
|
+
duration: clip.duration,
|
|
488
|
+
tracks: clip.tracks.map((track) => ({
|
|
489
|
+
type: track.type,
|
|
490
|
+
path: track.path,
|
|
491
|
+
times: [...track.times],
|
|
492
|
+
values: [...track.values]
|
|
493
|
+
}))
|
|
494
|
+
})),
|
|
495
|
+
animationPlaybacks: [...this.animationPlaybacks.values()].map((playback) => ({
|
|
496
|
+
nodeId: playback.nodeId,
|
|
497
|
+
clipName: playback.clipName,
|
|
498
|
+
loop: playback.loop,
|
|
499
|
+
active: playback.active,
|
|
500
|
+
playing: playback.active && !playback.paused,
|
|
501
|
+
paused: playback.paused,
|
|
502
|
+
timeScale: playback.timeScale,
|
|
503
|
+
hasMixer: playback.mixer !== null
|
|
504
|
+
})),
|
|
505
|
+
nodes: [...this.nodes.values()].map((node) => ({
|
|
506
|
+
id: node.id,
|
|
507
|
+
type: node.type,
|
|
508
|
+
parentId: node.parentId,
|
|
509
|
+
children: [...node.children],
|
|
510
|
+
classes: [...node.classes].sort(),
|
|
511
|
+
data: Object.fromEntries([...node.data.entries()].sort()),
|
|
512
|
+
attributes: Object.fromEntries([...node.attributes.entries()].sort())
|
|
513
|
+
}))
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
private resetGraph(): void {
|
|
518
|
+
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
519
|
+
this.stopPlayback(key, true);
|
|
520
|
+
}
|
|
521
|
+
this.nodes.clear();
|
|
522
|
+
this.nodes.set(ROOT_ID, {
|
|
523
|
+
id: ROOT_ID,
|
|
524
|
+
type: 'scene',
|
|
525
|
+
parentId: null,
|
|
526
|
+
children: [],
|
|
527
|
+
classes: new Set(),
|
|
528
|
+
data: new Map(),
|
|
529
|
+
attributes: new Map([
|
|
530
|
+
['embedded', 'true'],
|
|
531
|
+
['renderer', 'alpha: true']
|
|
532
|
+
]),
|
|
533
|
+
element: null
|
|
534
|
+
});
|
|
535
|
+
this.eventQueue.length = 0;
|
|
536
|
+
this.lastEvent = null;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private addNodeTree(template: TemplateNode, parentId: string, fallbackId: string): SceneNode {
|
|
540
|
+
const node = this.addNode({...template, id: fallbackId}, parentId);
|
|
541
|
+
for (const [index, child] of (template.children ?? []).entries()) {
|
|
542
|
+
const childId = child.id ?? child.type ?? String(index + 1);
|
|
543
|
+
this.addNodeTree(child, node.id, `${node.id}-${this.normalizeId(childId)}`);
|
|
544
|
+
}
|
|
545
|
+
return node;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
private addNode(template: TemplateNode, parentId: string): SceneNode {
|
|
549
|
+
const id = this.normalizeId(template.id ?? template.type ?? 'node');
|
|
550
|
+
if (id === ROOT_ID || this.nodes.has(id)) {
|
|
551
|
+
throw new Error(`Duplicate A-Frame node id: ${id}`);
|
|
552
|
+
}
|
|
553
|
+
const parent = this.requireNode(parentId);
|
|
554
|
+
const node: SceneNode = {
|
|
555
|
+
id,
|
|
556
|
+
type: this.normalizeNodeType(template.type ?? 'group'),
|
|
557
|
+
parentId,
|
|
558
|
+
children: [],
|
|
559
|
+
classes: new Set(this.normalizeClasses(template)),
|
|
560
|
+
data: new Map(this.normalizeRecord(template.data, this.normalizeDataKey.bind(this))),
|
|
561
|
+
attributes: new Map(
|
|
562
|
+
this.normalizeRecord(template.attributes, this.normalizeAttributeName.bind(this))
|
|
563
|
+
),
|
|
564
|
+
element: this.createElementForType(template.type ?? 'group')
|
|
565
|
+
};
|
|
566
|
+
this.nodes.set(id, node);
|
|
567
|
+
parent.children.push(id);
|
|
568
|
+
this.attachElement(parent, node);
|
|
569
|
+
this.attachNodeEventListeners(node);
|
|
570
|
+
this.applyNodeToElement(node);
|
|
571
|
+
return node;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
private deleteNode(id: string): void {
|
|
575
|
+
const node = this.requireNode(id);
|
|
576
|
+
for (const childId of [...node.children]) {
|
|
577
|
+
this.deleteNode(childId);
|
|
578
|
+
}
|
|
579
|
+
if (node.parentId !== null) {
|
|
580
|
+
const parent = this.requireNode(node.parentId);
|
|
581
|
+
parent.children = parent.children.filter((childId) => childId !== id);
|
|
582
|
+
}
|
|
583
|
+
node.element?.remove();
|
|
584
|
+
this.nodes.delete(id);
|
|
585
|
+
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
586
|
+
if (key.startsWith(`${id}:`)) {
|
|
587
|
+
this.stopPlayback(key, true);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
private matches(selector: string): SceneNode[] {
|
|
593
|
+
const normalized = selector.trim();
|
|
594
|
+
if (normalized.length === 0 || normalized === '*') return [...this.nodes.values()];
|
|
595
|
+
return [...this.nodes.values()].filter((node) => this.matchesSelector(node, normalized));
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
private firstMatch(selector: string): SceneNode | undefined {
|
|
599
|
+
return this.matches(selector)[0];
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
private matchesSelector(node: SceneNode, selector: string): boolean {
|
|
603
|
+
if (selector === '@event' || selector === 'event target') {
|
|
604
|
+
return this.lastEvent?.targetId === node.id;
|
|
605
|
+
}
|
|
606
|
+
if (selector.startsWith('#')) return node.id === this.normalizeId(selector.slice(1));
|
|
607
|
+
if (selector.startsWith('.')) return node.classes.has(this.normalizeToken(selector.slice(1)));
|
|
608
|
+
const dataMatch = selector.match(/^\[data-([a-zA-Z0-9_-]+)=["']?([^"'\]]+)["']?\]$/);
|
|
609
|
+
if (dataMatch !== null) {
|
|
610
|
+
const [, key, value] = dataMatch;
|
|
611
|
+
return node.data.get(this.normalizeDataKey(key ?? '')) === value;
|
|
612
|
+
}
|
|
613
|
+
return node.id === this.normalizeId(selector);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
private enqueueEvent(event: SceneEvent): void {
|
|
617
|
+
this.pushEvent(event);
|
|
618
|
+
const target = this.nodes.get(event.targetId);
|
|
619
|
+
const element = target?.element;
|
|
620
|
+
if (element !== null && element !== undefined) {
|
|
621
|
+
element.dispatchEvent(
|
|
622
|
+
new CustomEvent(event.type, {
|
|
623
|
+
detail: {data: event.data, targetId: event.targetId, twAframeSynthetic: true}
|
|
624
|
+
})
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
private pushEvent(event: SceneEvent): void {
|
|
630
|
+
this.eventQueue.push(event);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
private createSceneElement(): Element | null {
|
|
634
|
+
if (typeof document === 'undefined') return null;
|
|
635
|
+
const existing = document.getElementById('tw-aframe-root');
|
|
636
|
+
existing?.remove();
|
|
637
|
+
|
|
638
|
+
const host = document.createElement('div');
|
|
639
|
+
host.id = 'tw-aframe-root';
|
|
640
|
+
host.dataset['twAframeLayer'] = this.sceneOptions.layer;
|
|
641
|
+
host.dataset['twAframeMode'] = this.sceneOptions.mode;
|
|
642
|
+
host.style.position = 'absolute';
|
|
643
|
+
host.style.inset = '0';
|
|
644
|
+
host.style.pointerEvents = 'auto';
|
|
645
|
+
host.style.zIndex = this.sceneOptions.layer === 'below-stage' ? '0' : '10';
|
|
646
|
+
|
|
647
|
+
const scene = document.createElement('a-scene');
|
|
648
|
+
host.append(scene);
|
|
649
|
+
const mount = this.findStageMount();
|
|
650
|
+
mount.append(host);
|
|
651
|
+
return scene;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
private createElementForType(type: string): Element | null {
|
|
655
|
+
if (typeof document === 'undefined') return null;
|
|
656
|
+
return document.createElement(this.tagForType(this.normalizeNodeType(type)));
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
private attachElement(parent: SceneNode, child: SceneNode): void {
|
|
660
|
+
if (parent.element === null || child.element === null) return;
|
|
661
|
+
parent.element.append(child.element);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
private attachDomEventType(type: string): void {
|
|
665
|
+
for (const node of this.nodes.values()) {
|
|
666
|
+
this.attachNodeEventListener(node, type);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
private attachNodeEventListeners(node: SceneNode): void {
|
|
671
|
+
for (const type of this.domEventTypes) {
|
|
672
|
+
this.attachNodeEventListener(node, type);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private attachNodeEventListener(node: SceneNode, type: string): void {
|
|
677
|
+
const element = node.element;
|
|
678
|
+
if (element === null) return;
|
|
679
|
+
const listenerKey = `twAframeListener${type}`;
|
|
680
|
+
const elementWithState = element as Element & Record<string, boolean>;
|
|
681
|
+
if (elementWithState[listenerKey]) return;
|
|
682
|
+
element.addEventListener(type, (event) => {
|
|
683
|
+
if (event.target !== element) return;
|
|
684
|
+
const detail = this.eventDetail(event);
|
|
685
|
+
if (detail['twAframeSynthetic'] === true) return;
|
|
686
|
+
this.pushEvent({
|
|
687
|
+
type,
|
|
688
|
+
targetId: node.id,
|
|
689
|
+
data: JSON.stringify(detail)
|
|
690
|
+
});
|
|
691
|
+
});
|
|
692
|
+
elementWithState[listenerKey] = true;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
private eventDetail(event: Event): Record<string, unknown> {
|
|
696
|
+
if ('detail' in event && typeof event.detail === 'object' && event.detail !== null) {
|
|
697
|
+
return event.detail as Record<string, unknown>;
|
|
698
|
+
}
|
|
699
|
+
return {};
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
private findStageMount(): HTMLElement {
|
|
703
|
+
const selectors = [
|
|
704
|
+
'[class*="stage_stage-wrapper"]',
|
|
705
|
+
'[class*="stage-wrapper"]',
|
|
706
|
+
'[class*="stage"]',
|
|
707
|
+
'#scratch-stage',
|
|
708
|
+
'canvas'
|
|
709
|
+
];
|
|
710
|
+
for (const selector of selectors) {
|
|
711
|
+
const match = document.querySelector(selector);
|
|
712
|
+
const mount = match instanceof HTMLCanvasElement ? match.parentElement : match;
|
|
713
|
+
if (mount instanceof HTMLElement) {
|
|
714
|
+
const style = getComputedStyle(mount);
|
|
715
|
+
if (style.position === 'static') {
|
|
716
|
+
mount.style.position = 'relative';
|
|
717
|
+
}
|
|
718
|
+
return mount;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return document.body;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
private applyNodeToElement(node: SceneNode): void {
|
|
725
|
+
if (node.element === null) return;
|
|
726
|
+
node.element.id = node.id;
|
|
727
|
+
node.element.setAttribute('class', [...node.classes].sort().join(' '));
|
|
728
|
+
for (const [key, value] of node.data) {
|
|
729
|
+
node.element.setAttribute(`data-${key}`, value);
|
|
730
|
+
}
|
|
731
|
+
for (const [name, value] of node.attributes) {
|
|
732
|
+
node.element.setAttribute(name, value);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
private addKeyframeTrack(
|
|
737
|
+
args: {CLIP: unknown; PATH: unknown; TIMES: unknown; VALUES: unknown},
|
|
738
|
+
trackType: KeyframeTrackType
|
|
739
|
+
): void {
|
|
740
|
+
const times = this.parseNumberList(Scratch.Cast.toString(args.TIMES), 'times');
|
|
741
|
+
const values = this.parseNumberList(Scratch.Cast.toString(args.VALUES), 'values');
|
|
742
|
+
this.validateTrackNumbers(times, values, trackType === 'vector' ? 3 : 4);
|
|
743
|
+
this.pushKeyframeTrack({
|
|
744
|
+
clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
|
|
745
|
+
path: Scratch.Cast.toString(args.PATH),
|
|
746
|
+
trackType,
|
|
747
|
+
times,
|
|
748
|
+
values
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
private insertVectorKeyframe(
|
|
753
|
+
args: {CLIP: unknown; TIME: unknown; X: unknown; Y: unknown; Z: unknown},
|
|
754
|
+
path: '.position' | '.scale'
|
|
755
|
+
): void {
|
|
756
|
+
this.insertKeyframe({
|
|
757
|
+
clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
|
|
758
|
+
path,
|
|
759
|
+
trackType: 'vector',
|
|
760
|
+
time: Scratch.Cast.toNumber(args.TIME),
|
|
761
|
+
values: [
|
|
762
|
+
Scratch.Cast.toNumber(args.X),
|
|
763
|
+
Scratch.Cast.toNumber(args.Y),
|
|
764
|
+
Scratch.Cast.toNumber(args.Z)
|
|
765
|
+
]
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
private insertKeyframe({
|
|
770
|
+
clipName,
|
|
771
|
+
path,
|
|
772
|
+
trackType,
|
|
773
|
+
time,
|
|
774
|
+
values
|
|
775
|
+
}: {
|
|
776
|
+
clipName: string;
|
|
777
|
+
path: string;
|
|
778
|
+
trackType: KeyframeTrackType;
|
|
779
|
+
time: number;
|
|
780
|
+
values: readonly number[];
|
|
781
|
+
}): void {
|
|
782
|
+
if (!Number.isFinite(time) || time < 0) {
|
|
783
|
+
throw new TypeError('Animation keyframe time must be a non-negative number.');
|
|
784
|
+
}
|
|
785
|
+
if (values.some((value) => !Number.isFinite(value))) {
|
|
786
|
+
throw new TypeError('Animation keyframe values must be finite numbers.');
|
|
787
|
+
}
|
|
788
|
+
const stride = trackType === 'vector' ? 3 : 4;
|
|
789
|
+
if (values.length !== stride) {
|
|
790
|
+
throw new TypeError(`Animation keyframe must contain ${stride} values.`);
|
|
791
|
+
}
|
|
792
|
+
const clip = this.requireAnimationClip(clipName);
|
|
793
|
+
const normalizedPath = this.normalizeTrackPath(path, trackType);
|
|
794
|
+
let track = clip.tracks.find(
|
|
795
|
+
(item) => item.type === trackType && item.path === normalizedPath
|
|
796
|
+
);
|
|
797
|
+
if (track === undefined) {
|
|
798
|
+
track = {type: trackType, path: normalizedPath, times: [], values: []};
|
|
799
|
+
clip.tracks.push(track);
|
|
800
|
+
}
|
|
801
|
+
const insertAt = track.times.findIndex((existingTime) => existingTime >= time);
|
|
802
|
+
const valueInsertAt = (insertAt < 0 ? track.times.length : insertAt) * stride;
|
|
803
|
+
if (insertAt >= 0 && track.times[insertAt] === time) {
|
|
804
|
+
track.values.splice(valueInsertAt, stride, ...values);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const timeInsertAt = insertAt < 0 ? track.times.length : insertAt;
|
|
808
|
+
track.times.splice(timeInsertAt, 0, time);
|
|
809
|
+
track.values.splice(valueInsertAt, 0, ...values);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
private pushKeyframeTrack({
|
|
813
|
+
clipName,
|
|
814
|
+
path,
|
|
815
|
+
trackType,
|
|
816
|
+
times,
|
|
817
|
+
values
|
|
818
|
+
}: {
|
|
819
|
+
clipName: string;
|
|
820
|
+
path: string;
|
|
821
|
+
trackType: KeyframeTrackType;
|
|
822
|
+
times: number[];
|
|
823
|
+
values: number[];
|
|
824
|
+
}): void {
|
|
825
|
+
const clip = this.requireAnimationClip(clipName);
|
|
826
|
+
const normalizedPath = this.normalizeTrackPath(path, trackType);
|
|
827
|
+
clip.tracks.push({
|
|
828
|
+
type: trackType,
|
|
829
|
+
path: normalizedPath,
|
|
830
|
+
times: [...times],
|
|
831
|
+
values: [...values]
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
private parseNumberList(source: string, label: string): number[] {
|
|
836
|
+
const trimmed = source.trim();
|
|
837
|
+
if (trimmed.length === 0) {
|
|
838
|
+
throw new TypeError(`Animation ${label} must contain at least one number.`);
|
|
839
|
+
}
|
|
840
|
+
const values = trimmed
|
|
841
|
+
.split(/[\s,]+/)
|
|
842
|
+
.filter((part) => part.length > 0)
|
|
843
|
+
.map((part) => Number(part));
|
|
844
|
+
if (values.length === 0 || values.some((value) => !Number.isFinite(value))) {
|
|
845
|
+
throw new TypeError(`Animation ${label} must contain only finite numbers.`);
|
|
846
|
+
}
|
|
847
|
+
return values;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
private validateTrackNumbers(times: number[], values: number[], stride: number): void {
|
|
851
|
+
if (times.length === 0) {
|
|
852
|
+
throw new TypeError('Animation track times must not be empty.');
|
|
853
|
+
}
|
|
854
|
+
for (let index = 1; index < times.length; index += 1) {
|
|
855
|
+
if ((times[index] ?? 0) < (times[index - 1] ?? 0)) {
|
|
856
|
+
throw new TypeError('Animation track times must be sorted in ascending order.');
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
const expectedValues = times.length * stride;
|
|
860
|
+
if (values.length !== expectedValues) {
|
|
861
|
+
throw new TypeError(
|
|
862
|
+
`Animation track values length must be ${expectedValues} for ${times.length} keyframes.`
|
|
863
|
+
);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
private normalizeTrackPath(path: string, trackType: KeyframeTrackType): string {
|
|
868
|
+
const normalized = path.trim();
|
|
869
|
+
const allowed =
|
|
870
|
+
trackType === 'vector' ? new Set(['.position', '.scale']) : new Set(['.quaternion']);
|
|
871
|
+
if (!allowed.has(normalized)) {
|
|
872
|
+
throw new TypeError(
|
|
873
|
+
`Animation ${trackType} track path must be one of: ${[...allowed].join(', ')}.`
|
|
874
|
+
);
|
|
875
|
+
}
|
|
876
|
+
return normalized;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
private eulerToQuaternion(
|
|
880
|
+
x: number,
|
|
881
|
+
y: number,
|
|
882
|
+
z: number,
|
|
883
|
+
unit: 'degrees' | 'radians'
|
|
884
|
+
): [number, number, number, number] {
|
|
885
|
+
const scale = unit === 'degrees' ? Math.PI / 180 : 1;
|
|
886
|
+
const halfX = (x * scale) / 2;
|
|
887
|
+
const halfY = (y * scale) / 2;
|
|
888
|
+
const halfZ = (z * scale) / 2;
|
|
889
|
+
const c1 = Math.cos(halfX);
|
|
890
|
+
const c2 = Math.cos(halfY);
|
|
891
|
+
const c3 = Math.cos(halfZ);
|
|
892
|
+
const s1 = Math.sin(halfX);
|
|
893
|
+
const s2 = Math.sin(halfY);
|
|
894
|
+
const s3 = Math.sin(halfZ);
|
|
895
|
+
return [
|
|
896
|
+
s1 * c2 * c3 + c1 * s2 * s3,
|
|
897
|
+
c1 * s2 * c3 - s1 * c2 * s3,
|
|
898
|
+
c1 * c2 * s3 + s1 * s2 * c3,
|
|
899
|
+
c1 * c2 * c3 - s1 * s2 * s3
|
|
900
|
+
];
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
private normalizeEulerUnit(value: string): 'degrees' | 'radians' {
|
|
904
|
+
const unit = value.trim().toLowerCase();
|
|
905
|
+
if (unit !== 'radians' && unit !== 'degrees') {
|
|
906
|
+
throw new TypeError('Euler rotation keyframe unit must be radians or degrees.');
|
|
907
|
+
}
|
|
908
|
+
return unit;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
private createPlayback(
|
|
912
|
+
node: SceneNode,
|
|
913
|
+
clip: AnimationClipDefinition,
|
|
914
|
+
loop: boolean
|
|
915
|
+
): AnimationPlayback {
|
|
916
|
+
const key = this.playbackKey(node.id, clip.name);
|
|
917
|
+
this.stopPlayback(key, true);
|
|
918
|
+
const playback: AnimationPlayback = {
|
|
919
|
+
nodeId: node.id,
|
|
920
|
+
clipName: clip.name,
|
|
921
|
+
loop,
|
|
922
|
+
active: false,
|
|
923
|
+
paused: false,
|
|
924
|
+
timeScale: 1,
|
|
925
|
+
mixer: null,
|
|
926
|
+
action: null
|
|
927
|
+
};
|
|
928
|
+
const mixer = this.createMixer(node, clip, loop);
|
|
929
|
+
if (mixer !== null) {
|
|
930
|
+
playback.mixer = mixer.mixer;
|
|
931
|
+
playback.action = mixer.action;
|
|
932
|
+
playback.active = true;
|
|
933
|
+
}
|
|
934
|
+
return playback;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
private createMixer(
|
|
938
|
+
node: SceneNode,
|
|
939
|
+
clip: AnimationClipDefinition,
|
|
940
|
+
loop: boolean
|
|
941
|
+
): {mixer: AnimationMixerLike; action: AnimationActionLike} | null {
|
|
942
|
+
const object3D = this.object3DForNode(node);
|
|
943
|
+
const THREE = this.getThree();
|
|
944
|
+
if (object3D === null || THREE === null) return null;
|
|
945
|
+
const threeClip = this.toThreeAnimationClip(THREE, clip);
|
|
946
|
+
const mixer = new THREE.AnimationMixer(object3D);
|
|
947
|
+
const action = mixer.clipAction(threeClip);
|
|
948
|
+
if (action.setLoop !== undefined) {
|
|
949
|
+
action.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, loop ? Infinity : 1);
|
|
950
|
+
}
|
|
951
|
+
action.paused = false;
|
|
952
|
+
action.timeScale = 1;
|
|
953
|
+
action.play?.();
|
|
954
|
+
return {mixer, action};
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
private toThreeAnimationClip(THREE: ThreeAnimationApi, clip: AnimationClipDefinition): unknown {
|
|
958
|
+
const tracks = clip.tracks.map((track) => {
|
|
959
|
+
if (track.type === 'vector') {
|
|
960
|
+
return new THREE.VectorKeyframeTrack(track.path, track.times, track.values);
|
|
961
|
+
}
|
|
962
|
+
return new THREE.QuaternionKeyframeTrack(track.path, track.times, track.values);
|
|
963
|
+
});
|
|
964
|
+
return new THREE.AnimationClip(clip.name, clip.duration, tracks);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
private object3DForNode(node: SceneNode): unknown | null {
|
|
968
|
+
const element = node.element as (Element & {object3D?: unknown}) | null;
|
|
969
|
+
return element?.object3D ?? null;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
private stopPlayback(key: string, remove: boolean): void {
|
|
973
|
+
const playback = this.animationPlaybacks.get(key);
|
|
974
|
+
if (playback === undefined) return;
|
|
975
|
+
playback.action?.stop?.();
|
|
976
|
+
playback.mixer?.stopAllAction?.();
|
|
977
|
+
playback.active = false;
|
|
978
|
+
playback.paused = false;
|
|
979
|
+
if (remove) {
|
|
980
|
+
this.animationPlaybacks.delete(key);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
private stopClipEverywhere(clipName: string): void {
|
|
985
|
+
for (const [key, playback] of [...this.animationPlaybacks.entries()]) {
|
|
986
|
+
if (playback.clipName === clipName) {
|
|
987
|
+
this.stopPlayback(key, true);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
private updateAnimationMixers(deltaTime: number): void {
|
|
993
|
+
if (!Number.isFinite(deltaTime) || deltaTime < 0) return;
|
|
994
|
+
for (const playback of this.animationPlaybacks.values()) {
|
|
995
|
+
if (!playback.active || playback.paused) continue;
|
|
996
|
+
playback.mixer?.update(deltaTime * playback.timeScale);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
private ensureAnimationTickBridge(): void {
|
|
1001
|
+
const scene = this.rootElement;
|
|
1002
|
+
if (scene === null || this.getThree() === null) return;
|
|
1003
|
+
const AFRAME = this.getAFrame();
|
|
1004
|
+
if (AFRAME === null) return;
|
|
1005
|
+
const runtimes = this.animationRuntimeRegistry();
|
|
1006
|
+
runtimes.set(this.runtimeId, this);
|
|
1007
|
+
if (AFRAME.components?.['tw-animation-runtime'] === undefined) {
|
|
1008
|
+
AFRAME.registerComponent('tw-animation-runtime', {
|
|
1009
|
+
schema: {id: {type: 'string'}},
|
|
1010
|
+
tick(this: {data: {id: string}}, _time: number, timeDelta: number) {
|
|
1011
|
+
const extension = animationRuntimeRegistry().get(this.data.id);
|
|
1012
|
+
extension?.updateAnimationMixers(timeDelta / 1000);
|
|
1013
|
+
}
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
scene.setAttribute('tw-animation-runtime', `id: ${this.runtimeId}`);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
private animationRuntimeRegistry(): Map<string, TurboWarpAFrameExtension> {
|
|
1020
|
+
return animationRuntimeRegistry();
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
private getAFrame(): AFrameApi | null {
|
|
1024
|
+
const value = (globalThis as {AFRAME?: AFrameApi}).AFRAME;
|
|
1025
|
+
return value ?? null;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
private getThree(): ThreeAnimationApi | null {
|
|
1029
|
+
return this.getAFrame()?.THREE ?? null;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
private playbackKey(nodeId: string, clipName: string): string {
|
|
1033
|
+
return `${nodeId}:${clipName}`;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
private requireAnimationClip(name: string): AnimationClipDefinition {
|
|
1037
|
+
const clip = this.animationClips.get(name);
|
|
1038
|
+
if (clip === undefined) {
|
|
1039
|
+
throw new Error(`Unknown 3D animation clip: ${name}`);
|
|
1040
|
+
}
|
|
1041
|
+
return clip;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
private setVec3Attribute(selector: string, name: string, value: Vec3): void {
|
|
1045
|
+
for (const node of this.matches(selector)) {
|
|
1046
|
+
this.setVec3(node, name, value);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
private setVec3(node: SceneNode, name: string, value: Vec3): void {
|
|
1051
|
+
node.attributes.set(name, `${value.x} ${value.y} ${value.z}`);
|
|
1052
|
+
this.applyNodeToElement(node);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
private argsToVec3(args: {X: unknown; Y: unknown; Z: unknown}): Vec3 {
|
|
1056
|
+
return {
|
|
1057
|
+
x: Scratch.Cast.toNumber(args.X),
|
|
1058
|
+
y: Scratch.Cast.toNumber(args.Y),
|
|
1059
|
+
z: Scratch.Cast.toNumber(args.Z)
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
private parseVec3(value: string | undefined): Vec3 {
|
|
1064
|
+
if (value === undefined) return {x: 0, y: 0, z: 0};
|
|
1065
|
+
const [x = 0, y = 0, z = 0] = value.split(/\s+/).map((part) => Number(part));
|
|
1066
|
+
return {x, y, z};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
private parseTemplate(source: string): TemplateNode {
|
|
1070
|
+
const value: unknown = JSON.parse(source);
|
|
1071
|
+
this.validateTemplateNode(value, 'template');
|
|
1072
|
+
return value as TemplateNode;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
private validateTemplateNode(value: unknown, path: string): asserts value is TemplateNode {
|
|
1076
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
1077
|
+
throw new TypeError(`A-Frame ${path} must be an object.`);
|
|
1078
|
+
}
|
|
1079
|
+
const node = value as Record<string, unknown>;
|
|
1080
|
+
for (const key of Object.keys(node)) {
|
|
1081
|
+
if (!TEMPLATE_NODE_KEYS.has(key)) {
|
|
1082
|
+
throw new TypeError(`A-Frame ${path}.${key} is not supported.`);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
this.validateOptionalString(node['type'], `${path}.type`);
|
|
1086
|
+
this.validateOptionalString(node['id'], `${path}.id`);
|
|
1087
|
+
this.validateTemplateClass(node['class'], `${path}.class`);
|
|
1088
|
+
this.validateOptionalStringArray(node['classes'], `${path}.classes`);
|
|
1089
|
+
this.validateStringRecord(node['data'], `${path}.data`);
|
|
1090
|
+
this.validateStringRecord(node['attributes'], `${path}.attributes`);
|
|
1091
|
+
const children = node['children'];
|
|
1092
|
+
if (children === undefined) return;
|
|
1093
|
+
if (!Array.isArray(children)) {
|
|
1094
|
+
throw new TypeError(`A-Frame ${path}.children must be an array.`);
|
|
1095
|
+
}
|
|
1096
|
+
children.forEach((child, index) => {
|
|
1097
|
+
this.validateTemplateNode(child, `${path}.children[${index}]`);
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
private validateTemplateClass(value: unknown, path: string): void {
|
|
1102
|
+
if (value === undefined || typeof value === 'string') return;
|
|
1103
|
+
if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
|
|
1104
|
+
throw new TypeError(`A-Frame ${path} must be a string or string array.`);
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
private validateOptionalStringArray(value: unknown, path: string): void {
|
|
1108
|
+
if (value === undefined) return;
|
|
1109
|
+
if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
|
|
1110
|
+
throw new TypeError(`A-Frame ${path} must be a string array.`);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
private validateOptionalString(value: unknown, path: string): void {
|
|
1114
|
+
if (value === undefined || typeof value === 'string') return;
|
|
1115
|
+
throw new TypeError(`A-Frame ${path} must be a string.`);
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
private validateStringRecord(value: unknown, path: string): void {
|
|
1119
|
+
if (value === undefined) return;
|
|
1120
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
1121
|
+
throw new TypeError(`A-Frame ${path} must be an object.`);
|
|
1122
|
+
}
|
|
1123
|
+
for (const [key, recordValue] of Object.entries(value)) {
|
|
1124
|
+
if (key.trim().length === 0) {
|
|
1125
|
+
throw new TypeError(`A-Frame ${path} keys must be non-empty strings.`);
|
|
1126
|
+
}
|
|
1127
|
+
if (recordValue === undefined) {
|
|
1128
|
+
throw new TypeError(`A-Frame ${path}.${key} must not be undefined.`);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
private normalizeClasses(template: TemplateNode): string[] {
|
|
1134
|
+
const classes = [
|
|
1135
|
+
...(Array.isArray(template.class) ? template.class : String(template.class ?? '').split(/\s+/)),
|
|
1136
|
+
...(template.classes ?? [])
|
|
1137
|
+
];
|
|
1138
|
+
return classes.map((value) => this.normalizeToken(value)).filter((value) => value.length > 0);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
private normalizeRecord(
|
|
1142
|
+
value: Record<string, unknown> | undefined,
|
|
1143
|
+
normalizeKey: (key: string) => string
|
|
1144
|
+
): Array<[string, string]> {
|
|
1145
|
+
return Object.entries(value ?? {}).map(([key, recordValue]) => [
|
|
1146
|
+
normalizeKey(key),
|
|
1147
|
+
String(recordValue)
|
|
1148
|
+
]);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
private normalizeNodeType(value: string): string {
|
|
1152
|
+
const type = this.normalizeToken(value);
|
|
1153
|
+
return type.length === 0 ? 'group' : type;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
private normalizeId(value: string): string {
|
|
1157
|
+
return this.normalizeToken(value) || 'node';
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
private normalizeToken(value: string): string {
|
|
1161
|
+
return value.trim().replace(/[^a-zA-Z0-9_-]/g, '-');
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
private normalizeDataKey(value: string): string {
|
|
1165
|
+
return this.normalizeToken(value).toLowerCase();
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
private normalizeAttributeName(value: string): string {
|
|
1169
|
+
return value.trim().replace(/[^a-zA-Z0-9_:-]/g, '-');
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
private tagForType(type: string): string {
|
|
1173
|
+
const tags: Record<string, string> = {
|
|
1174
|
+
box: 'a-box',
|
|
1175
|
+
camera: 'a-camera',
|
|
1176
|
+
circle: 'a-circle',
|
|
1177
|
+
cone: 'a-cone',
|
|
1178
|
+
cylinder: 'a-cylinder',
|
|
1179
|
+
empty: 'a-entity',
|
|
1180
|
+
group: 'a-entity',
|
|
1181
|
+
image: 'a-image',
|
|
1182
|
+
'image-plane': 'a-image',
|
|
1183
|
+
light: 'a-light',
|
|
1184
|
+
model: 'a-entity',
|
|
1185
|
+
plane: 'a-plane',
|
|
1186
|
+
primitive: 'a-entity',
|
|
1187
|
+
scene: 'a-scene',
|
|
1188
|
+
sphere: 'a-sphere',
|
|
1189
|
+
text: 'a-text'
|
|
1190
|
+
};
|
|
1191
|
+
return tags[type] ?? 'a-entity';
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
private requireNode(id: string): SceneNode {
|
|
1195
|
+
const node = this.nodes.get(id);
|
|
1196
|
+
if (node === undefined) {
|
|
1197
|
+
throw new Error(`Unknown A-Frame node: ${id}`);
|
|
1198
|
+
}
|
|
1199
|
+
return node;
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
private toScratchBlock(block: BlockDefinition): Record<string, unknown> {
|
|
1203
|
+
return {
|
|
1204
|
+
opcode: block.opcode,
|
|
1205
|
+
blockType: Scratch.BlockType[block.blockType],
|
|
1206
|
+
text: Scratch.translate(block.text),
|
|
1207
|
+
arguments: Object.fromEntries(
|
|
1208
|
+
Object.entries(block.arguments).map(([name, argument]) => [
|
|
1209
|
+
name,
|
|
1210
|
+
{
|
|
1211
|
+
type: Scratch.ArgumentType[argument.type],
|
|
1212
|
+
defaultValue: argument.defaultValue
|
|
1213
|
+
}
|
|
1214
|
+
])
|
|
1215
|
+
)
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
function animationRuntimeRegistry(): Map<string, TurboWarpAFrameExtension> {
|
|
1221
|
+
const globalState = globalThis as {
|
|
1222
|
+
__twAframeAnimationRuntimes?: Map<string, TurboWarpAFrameExtension>;
|
|
1223
|
+
};
|
|
1224
|
+
globalState.__twAframeAnimationRuntimes ??= new Map();
|
|
1225
|
+
return globalState.__twAframeAnimationRuntimes;
|
|
1226
|
+
}
|