forked from aws-samples/amazon-sumerian-hosts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
babylon.html
956 lines (857 loc) · 29 KB
/
babylon.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
<!--
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Babylon.js Host Test</title>
<style>
html,
body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border-color: black;
}
.tab {
background-color: rgb(219, 219, 219);
padding-bottom: 0px;
margin-bottom: -1px;
border-width: 1px;
border-style: solid;
z-index: 2;
position: relative;
outline: 0px;
}
.current {
background-color: white;
border-bottom-color: white;
font-weight: bold;
}
.textEntry {
min-width: 305px;
min-height: 200px;
outline: 0px;
padding: 10px;
resize: both;
}
.speechButton {
width: 78.75px;
}
.gestureButton {
width: 327px;
outline: 0px;
}
.hidden {
display: none;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
#textToSpeech {
padding: 2.5px;
position: fixed;
top: 0;
left: 0;
display: none;
}
#loadScreen {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background-image: url('assets/images/load_screen.png');
background-color: gray;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: contain;
z-index: 9999;
}
#loader {
border: 16px solid #3498db38;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 120px;
height: 120px;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
position: fixed;
}
@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<!--Text to speech dependency-->
<script
type="text/javascript"
src="https://sdk.amazonaws.com/js/aws-sdk-2.645.0.min.js"
></script>
<!--Babylon.js dependencies-->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
<!--Host build file-->
<script type="text/javascript" src="../dist/host.babylon.js"></script>
</head>
<body>
<!--Loading screen-->
<div id="loadScreen">
<div id="loader"></div>
</div>
<!--Text to speech controls-->
<div id="textToSpeech">
<button class="tab current" onclick="toggleHost(event)">Grace</button>
<button class="tab" onclick="toggleHost(event)">Alien</button>
<div>
<textarea autofocus size="23" type="text" class="textEntry Grace">
<speak>
<amazon:domain name="conversational">
Hello, my name is Grace. I used to only be a host inside Amazon Sumerian, but
now you can use me in other Javascript runtime environments like three js
and Babylon js. Right now,
<mark name='{"feature":"PointOfInterestFeature","method":"setTargetByName","args":["char:gaze"]}' />
my friend and I here are in Babylon js.
</amazon:domain>
</speak>
</textarea
>
<textarea autofocus size="23" type="text" class="textEntry Alien">
<speak>
Hi there! As you can see I'm set up to be a host too, although I don't use
the same type of skeleton as any of the original Amazon Sumerian hosts. With
open source hosts, you can apply host functionality to any custom animated
character you'd like. I'm excited to see what kinds of interesting host
characters you'll bring to life!
</speak>
</textarea
>
</div>
<div>
<button id="play" class="speechButton">Play</button>
<button id="pause" class="speechButton">Pause</button>
<button id="resume" class="speechButton">Resume</button>
<button id="stop" class="speechButton">Stop</button>
</div>
<div>
<button id="gestures" class="gestureButton">Generate Gestures</button>
</div>
<div>
<select id="emotes" class="gestureButton"></select>
</div>
<div>
<button id="playEmote" class="gestureButton">Play Emote</button>
</div>
</div>
<!--Create the Babylon.js scene-->
<script>
const speakers = new Map([
['Grace', undefined],
['Alien', undefined],
]);
main();
async function main() {
// Initialize AWS and create Polly service objects
window.AWS.config.region = 'us-west-2';
window.AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '<Enter Cognito Identity Pool ID here>',
});
const polly = new AWS.Polly();
const presigner = new AWS.Polly.Presigner();
const speechInit = HOST.aws.TextToSpeechFeature.initializeService(
polly,
presigner,
window.AWS.VERSION
);
// Define the glTF assets that will represent the hosts
const characterFile1 =
'./assets/glTF/characters/adult_female/grace/grace.gltf';
const characterFile2 = './assets/glTF/characters/alien/alien.gltf';
const animationPath1 = './assets/glTF/animations/adult_female';
const animationPath2 = './assets/glTF/animations/alien';
const animationFiles = [
'stand_idle.glb',
'lipsync.glb',
'gesture.glb',
'emote.glb',
'face_idle.glb',
'blink.glb',
'poi.glb',
];
const gestureConfigFile = 'gesture.json';
const poiConfigFile = 'poi.json';
const audioAttachJoint1 = 'char:def_c_neckB'; // Name of the joint to attach audio to
const audioAttachJoint2 = 'char:head';
const lookJoint1 = 'char:jx_c_look'; // Name of the joint to use for point of interest target tracking
const lookJoint2 = 'char:gaze';
const voice1 = 'Joanna'; // Polly voice. Full list of available voices at: https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
const voice2 = 'Ivy';
const voiceEngine = 'neural'; // Neural engine is not available for all voices in all regions: https://docs.aws.amazon.com/polly/latest/dg/NTTS-main.html
// Set up the scene and hosts
const {scene, camera} = createScene();
const {
character: character1,
clips: clips1,
bindPoseOffset: bindPoseOffset1,
} = await loadCharacter(
scene,
characterFile1,
animationPath1,
animationFiles
);
const {
character: character2,
clips: clips2,
bindPoseOffset: bindPoseOffset2,
} = await loadCharacter(
scene,
characterFile2,
animationPath2,
animationFiles
);
character1.position.x = 1.25;
character1.rotation.y = -0.5;
character2.position.x = -0.5;
character2.rotation.y = 0.5;
// Find the joints defined by name
const children1 = character1.getDescendants(false);
const audioAttach1 = children1.find(
child => child.name === audioAttachJoint1
);
const lookTracker1 = children1.find(child => child.name === lookJoint1);
const children2 = character2.getDescendants(false);
const audioAttach2 = children2.find(
child => child.name === audioAttachJoint2
);
const lookTracker2 = children2.find(child => child.name === lookJoint2);
// Read the gesture config file. This file contains options for splitting up
// each animation in gestures.glb into 3 sub-animations and initializing them
// as a QueueState animation.
const gestureConfig1 = await fetch(
`${animationPath1}/${gestureConfigFile}`
).then(response => response.json());
const gestureConfig2 = await fetch(
`${animationPath2}/${gestureConfigFile}`
).then(response => response.json());
// Read the point of interest config file. This file contains options for
// creating Blend2dStates from look pose clips and initializing look layers
// on the PointOfInterestFeature.
const poiConfig1 = await fetch(
`${animationPath1}/${poiConfigFile}`
).then(response => response.json());
const poiConfig2 = await fetch(
`${animationPath2}/${poiConfigFile}`
).then(response => response.json());
const [
idleClips1,
lipsyncClips1,
gestureClips1,
emoteClips1,
faceClips1,
blinkClips1,
poiClips1,
] = clips1;
const host1 = createHost(
character1,
audioAttach1,
voice1,
voiceEngine,
idleClips1[0],
faceClips1[0],
lipsyncClips1,
gestureClips1,
gestureConfig1,
emoteClips1,
blinkClips1,
poiClips1,
poiConfig1,
lookTracker1,
bindPoseOffset1,
scene,
camera
);
const [
idleClips2,
lipsyncClips2,
gestureClips2,
emoteClips2,
faceClips2,
blinkClips2,
poiClips2,
] = clips2;
const host2 = createHost(
character2,
audioAttach2,
voice2,
voiceEngine,
idleClips2[0],
faceClips2[0],
lipsyncClips2,
gestureClips2,
gestureConfig2,
emoteClips2,
blinkClips2,
poiClips2,
poiConfig2,
lookTracker2,
bindPoseOffset2,
scene,
camera
);
// Turn down blink layer weight to account for the difference in eyelid height between Grace and Fiona
host1.AnimationFeature.setLayerWeight('Blink', 0.5);
// Set up each host to look at the other when the other speaks and at the
// camera when speech ends
const onHost1StartSpeech = () => {
host2.PointOfInterestFeature.setTarget(lookTracker1);
};
const onHost2StartSpeech = () => {
host1.PointOfInterestFeature.setTarget(lookTracker2);
};
const onStopSpeech = () => {
host1.PointOfInterestFeature.setTarget(camera);
host2.PointOfInterestFeature.setTarget(camera);
};
host1.listenTo(
host1.TextToSpeechFeature.EVENTS.play,
onHost1StartSpeech
);
host1.listenTo(
host1.TextToSpeechFeature.EVENTS.resume,
onHost1StartSpeech
);
host2.listenTo(
host2.TextToSpeechFeature.EVENTS.play,
onHost2StartSpeech
);
host2.listenTo(
host2.TextToSpeechFeature.EVENTS.resume,
onHost2StartSpeech
);
HOST.aws.TextToSpeechFeature.listenTo(
HOST.aws.TextToSpeechFeature.EVENTS.pause,
onStopSpeech
);
HOST.aws.TextToSpeechFeature.listenTo(
HOST.aws.TextToSpeechFeature.EVENTS.stop,
onStopSpeech
);
// Hide the load screen and show the text input
document.getElementById('textToSpeech').style.display = 'inline-block';
document.getElementById('loadScreen').style.display = 'none';
// Wait for the TextToSpeechFeature to be ready
await speechInit;
speakers.set('Grace', host1);
speakers.set('Alien', host2);
initializeUX();
}
// Set up base scene
function createScene() {
// Canvas
const canvas = document.createElement('canvas');
canvas.id = 'renderCanvas';
canvas.style.width = `${window.innerWidth}px`;
canvas.style.height = `${window.innerHeight}px`;
document.body.appendChild(canvas);
// Scene
const engine = new BABYLON.Engine(canvas, true, undefined, true);
const scene = new BABYLON.Scene(engine);
scene.useRightHandedSystem = true;
scene.fogColor.set(0.5, 0.5, 0.5);
const assetManager = new BABYLON.AssetsManager(scene);
// Use our own button to enable audio
BABYLON.Engine.audioEngine.useCustomUnlockedButton = true;
// Handle window resize
window.addEventListener('resize', function() {
canvas.style.width = `${window.innerWidth}px`;
canvas.style.height = `${window.innerHeight}px`;
engine.resize();
});
engine.runRenderLoop(scene.render.bind(scene));
// Camera
const camera = new BABYLON.ArcRotateCamera(
'Camera',
Math.PI / 2,
Math.PI / 2,
1.4,
new BABYLON.Vector3(0, 1.4, 0),
scene
);
camera.minZ = 0.1;
camera.maxZ = 1000;
camera.setPosition(new BABYLON.Vector3(0, 1.4, 3.1));
camera.setTarget(new BABYLON.Vector3(0, 0.8, 0));
camera.wheelDeltaPercentage = 0.01;
camera.attachControl(canvas, true);
// Lights
var hemiLight = new BABYLON.HemisphericLight(
'light1',
new BABYLON.Vector3(0, 1, 0),
scene
);
hemiLight.intensity = 0.6;
hemiLight.specular = BABYLON.Color3.Black();
var dirLight = new BABYLON.DirectionalLight(
'dir01',
new BABYLON.Vector3(0, -0.5, -1.0),
scene
);
dirLight.position = new BABYLON.Vector3(0, 5, 5);
// Shadows
shadowGenerator = new BABYLON.ShadowGenerator(1024, dirLight);
shadowGenerator.useBlurExponentialShadowMap = true;
shadowGenerator.blurKernel = 32;
// Environment
var helper = scene.createDefaultEnvironment({
enableGroundShadow: true,
});
helper.groundMaterial.primaryColor.set(0.5, 0.5, 0.5);
helper.ground.receiveShadows = true;
return {scene, camera};
}
// Load character model and animations
async function loadCharacter(
scene,
characterFile,
animationPath,
animationFiles
) {
// Load character model
const {
character,
bindPoseOffset,
} = await BABYLON.SceneLoader.LoadAssetContainerAsync(
characterFile
).then(container => {
const [character] = container.meshes;
const [bindPoseOffset] = container.animationGroups;
// Make the offset pose additive
if (bindPoseOffset) {
BABYLON.AnimationGroup.MakeAnimationAdditive(bindPoseOffset);
}
// Add everything to the scene
container.scene = scene;
container.addAllToScene();
// Cast shadows but don't receive
shadowGenerator.addShadowCaster(character, true);
for (var index = 0; index < container.meshes.length; index++) {
container.meshes[index].receiveShadows = false;
}
return {character, bindPoseOffset};
});
const children = character.getDescendants(false);
// Load animations
const clips = await Promise.all(
animationFiles.map((filename, index) => {
const filePath = `${animationPath}/${filename}`;
return BABYLON.SceneLoader.LoadAssetContainerAsync(filePath).then(
container => {
const startingIndex = scene.animatables.length;
const firstIndex = scene.animationGroups.length;
// Apply animation to character
container.mergeAnimationsTo(
scene,
scene.animatables.slice(startingIndex),
target => children.find(c => c.name === target.name) || null
);
// Find the new animations and destroy the container
const animations = scene.animationGroups.slice(firstIndex);
container.dispose();
scene.onAnimationFileImportedObservable.notifyObservers(scene);
return animations;
}
);
})
);
return {character, clips, bindPoseOffset};
}
// Initialize the host
function createHost(
character,
audioAttachJoint,
voice,
engine,
idleClip,
faceIdleClip,
lipsyncClips,
gestureClips,
gestureConfig,
emoteClips,
blinkClips,
poiClips,
poiConfig,
lookJoint,
bindPoseOffset,
scene,
camera
) {
// Add the host to the render loop
const host = new HOST.HostObject({owner: character});
scene.onBeforeAnimationsObservable.add(() => {
host.update();
});
// Set up text to speech
host.addFeature(HOST.aws.TextToSpeechFeature, false, {
scene,
attachTo: audioAttachJoint,
voice,
engine,
});
// Set up animation
host.addFeature(HOST.anim.AnimationFeature);
// Base idle
host.AnimationFeature.addLayer('Base');
host.AnimationFeature.addAnimation(
'Base',
idleClip.name,
HOST.anim.AnimationTypes.single,
{clip: idleClip}
);
host.AnimationFeature.playAnimation('Base', idleClip.name);
// Face idle
host.AnimationFeature.addLayer('Face', {
blendMode: HOST.anim.LayerBlendModes.Additive,
});
BABYLON.AnimationGroup.MakeAnimationAdditive(faceIdleClip);
host.AnimationFeature.addAnimation(
'Face',
faceIdleClip.name,
HOST.anim.AnimationTypes.single,
{clip: faceIdleClip, from: 1 / 30, to: faceIdleClip.to}
);
host.AnimationFeature.playAnimation('Face', faceIdleClip.name);
// Blink
host.AnimationFeature.addLayer('Blink', {
blendMode: HOST.anim.LayerBlendModes.Additive,
transitionTime: 0.075,
});
blinkClips.forEach(clip => {
BABYLON.AnimationGroup.MakeAnimationAdditive(clip);
});
host.AnimationFeature.addAnimation(
'Blink',
'blink',
HOST.anim.AnimationTypes.randomAnimation,
{
playInterval: 3,
subStateOptions: blinkClips.map(clip => {
return {
name: clip.name,
loopCount: 1,
clip,
};
}),
}
);
host.AnimationFeature.playAnimation('Blink', 'blink');
// Talking idle
host.AnimationFeature.addLayer('Talk', {
transitionTime: 0.75,
blendMode: HOST.anim.LayerBlendModes.Additive,
});
host.AnimationFeature.setLayerWeight('Talk', 0);
const talkClip = lipsyncClips.find(c => c.name === 'stand_talk');
BABYLON.AnimationGroup.MakeAnimationAdditive(talkClip);
lipsyncClips.splice(lipsyncClips.indexOf(talkClip), 1);
host.AnimationFeature.addAnimation(
'Talk',
talkClip.name,
HOST.anim.AnimationTypes.single,
{clip: talkClip}
);
host.AnimationFeature.playAnimation('Talk', talkClip.name);
// Gesture animations
host.AnimationFeature.addLayer('Gesture', {
transitionTime: 0.5,
blendMode: HOST.anim.LayerBlendModes.Additive,
});
gestureClips.forEach(clip => {
const {name} = clip;
const config = gestureConfig[name];
BABYLON.AnimationGroup.MakeAnimationAdditive(clip);
if (config !== undefined) {
// Add the clip to each queueOption so it can be split up
config.queueOptions.forEach((option, index) => {
option.clip = clip;
option.to /= 30.0;
option.from /= 30.0;
});
host.AnimationFeature.addAnimation(
'Gesture',
name,
HOST.anim.AnimationTypes.queue,
config
);
} else {
host.AnimationFeature.addAnimation(
'Gesture',
name,
HOST.anim.AnimationTypes.single,
{clip}
);
}
});
// Emote animations
host.AnimationFeature.addLayer('Emote', {
transitionTime: 0.5,
});
emoteClips.forEach(clip => {
const {name} = clip;
host.AnimationFeature.addAnimation(
'Emote',
name,
HOST.anim.AnimationTypes.single,
{clip, loopCount: 1}
);
});
// Viseme poses
host.AnimationFeature.addLayer('Viseme', {
transitionTime: 0.12,
blendMode: HOST.anim.LayerBlendModes.Additive,
});
host.AnimationFeature.setLayerWeight('Viseme', 0);
const blendStateOptions = lipsyncClips.map(clip => {
BABYLON.AnimationGroup.MakeAnimationAdditive(clip);
return {
name: clip.name,
clip,
weight: 0,
from: 1 / 30,
to: 2 / 30,
};
});
host.AnimationFeature.addAnimation(
'Viseme',
'visemes',
HOST.anim.AnimationTypes.freeBlend,
{blendStateOptions}
);
host.AnimationFeature.playAnimation('Viseme', 'visemes');
// POI poses
const children = character.getDescendants(false);
poiConfig.forEach(config => {
host.AnimationFeature.addLayer(config.name, {
blendMode: HOST.anim.LayerBlendModes.Additive,
});
// Find each pose clip and make it additive
config.blendStateOptions.forEach(clipConfig => {
clip = poiClips.find(clip => clip.name === clipConfig.clip);
BABYLON.AnimationGroup.MakeAnimationAdditive(clip);
clipConfig.clip = clip;
clipConfig.from = 1 / 30;
clipConfig.to = 2 / 30;
});
host.AnimationFeature.addAnimation(
config.name,
config.animation,
HOST.anim.AnimationTypes.blend2d,
{...config}
);
host.AnimationFeature.playAnimation(config.name, config.animation);
// Find and store the reference object
config.reference = children.find(
child => child.name === config.reference
);
});
// Apply bindPoseOffset clip if it exists
if (bindPoseOffset !== undefined) {
host.AnimationFeature.addLayer('BindPoseOffset', {
blendMode: HOST.anim.LayerBlendModes.Additive,
});
host.AnimationFeature.addAnimation(
'BindPoseOffset',
bindPoseOffset.name,
HOST.anim.AnimationTypes.single,
{clip: bindPoseOffset, from: 1 / 30, to: 2 / 30}
);
host.AnimationFeature.playAnimation(
'BindPoseOffset',
bindPoseOffset.name
);
}
// Set up Lipsync
const visemeOptions = {
layers: [
{
name: 'Viseme',
animation: 'visemes',
},
],
};
const talkingOptions = {
layers: [
{
name: 'Talk',
animation: 'stand_talk',
blendTime: 0.75,
easingFn: HOST.anim.Easing.Quadratic.InOut,
},
],
};
host.addFeature(
HOST.LipsyncFeature,
false,
visemeOptions,
talkingOptions
);
// Set up Gestures
host.addFeature(HOST.GestureFeature, false, {
layers: {
Gesture: {minimumInterval: 3},
Emote: {
blendTime: 0.5,
easingFn: HOST.anim.Easing.Quadratic.InOut,
},
},
});
// Set up Point of Interest
host.addFeature(
HOST.PointOfInterestFeature,
false,
{
target: camera,
lookTracker: lookJoint,
scene,
},
{
layers: poiConfig,
},
{
layers: [{name: 'Blink'}],
}
);
return host;
}
// Return the host whose name matches the text of the current tab
function getCurrentHost() {
const tab = document.getElementsByClassName('tab current')[0];
const name = tab.textContent;
return {name, host: speakers.get(name)};
}
// Update UX with data for the current host
function toggleHost(evt) {
const tab = evt.target;
const allTabs = document.getElementsByClassName('tab');
// Update tab classes
for (let i = 0, l = allTabs.length; i < l; i++) {
if (allTabs[i] !== tab) {
allTabs[i].classList.remove('current');
} else {
allTabs[i].classList.add('current');
}
}
// Show/hide speech input classes
const {name, host} = getCurrentHost(speakers);
const textEntries = document.getElementsByClassName('textEntry');
for (let i = 0, l = textEntries.length; i < l; i += 1) {
const textEntry = textEntries[i];
if (textEntry.classList.contains(name)) {
textEntry.classList.remove('hidden');
} else {
textEntry.classList.add('hidden');
}
}
// Update emote selector
const emoteSelect = document.getElementById('emotes');
emoteSelect.length = 0;
const emotes = host.AnimationFeature.getAnimations('Emote');
emotes.forEach((emote, i) => {
const emoteOption = document.createElement('option');
emoteOption.text = emote;
emoteOption.value = emote;
emoteSelect.add(emoteOption, 0);
// Set the current item to the first emote
if (!i) {
emoteSelect.value = emote;
}
});
}
function initializeUX(speakers) {
// Enable drag/drop text files on the speech text area
enableDragDrop('textEntry');
// Play, pause, resume and stop the contents of the text input as speech
// when buttons are clicked
['play', 'pause', 'resume', 'stop'].forEach(id => {
const button = document.getElementById(id);
button.onclick = () => {
const {name, host} = getCurrentHost(speakers);
const speechInput = document.getElementsByClassName(
`textEntry ${name}`
)[0];
host.TextToSpeechFeature[id](speechInput.value);
};
});
// Update the text area text with gesture SSML markup when clicked
const gestureButton = document.getElementById('gestures');
gestureButton.onclick = () => {
const {name, host} = getCurrentHost(speakers);
const speechInput = document.getElementsByClassName(
`textEntry ${name}`
)[0];
const gestureMap = host.GestureFeature.createGestureMap();
const gestureArray = host.GestureFeature.createGenericGestureArray([
'Gesture',
]);
speechInput.value = HOST.aws.TextToSpeechUtils.autoGenerateSSMLMarks(
speechInput.value,
gestureMap,
gestureArray
);
};
// Play emote on demand with emote button
const emoteSelect = document.getElementById('emotes');
const emoteButton = document.getElementById('playEmote');
emoteButton.onclick = () => {
const {host} = getCurrentHost(speakers);
host.GestureFeature.playGesture('Emote', emoteSelect.value);
};
// Initialize tab
const tab = document.getElementsByClassName('tab current')[0];
toggleHost({target: tab});
}
function enableDragDrop(className) {
const elements = document.getElementsByClassName(className);
for (let i = 0, l = elements.length; i < l; i += 1) {
const dropArea = elements[i];
// Copy contents of files into the text input once they are read
const fileReader = new FileReader();
fileReader.onload = evt => {
dropArea.value = evt.target.result;
};
// Drag and drop listeners
dropArea.addEventListener('dragover', evt => {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
});
dropArea.addEventListener('drop', evt => {
evt.stopPropagation();
evt.preventDefault();
// Read the first file that was dropped
const [file] = evt.dataTransfer.files;
fileReader.readAsText(file, 'UTF-8');
});
}
}
</script>
</body>
</html>