-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathModelPlayer.js
1202 lines (1087 loc) · 56.2 KB
/
ModelPlayer.js
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class ModelPlayer{
/**
* @param {id of div containing the viewer} _divParent
* @param {player's id} _divPlayer
* @param {url of the model} _model
*/
constructor(_divParent, _divPlayer, _model, _poi, _pad, _environement){
this.parent = _divParent;
this.player = _divPlayer;
this.model = _model
this.poi = _poi ? _poi : null
// this.player = null
this.playerCtrl = null
this.sidebar = null
this.show = false;
this.cogs = null;
this.environement = _environement
this.multi = typeof _model === "object" ? true : false //if there is more than one model
this.x=0
this.y=0
this.z=0
this.loop = true;
this.pad = _pad ? _pad : true;
this.fullOn=false
}
buildPlayer(id){
const player = document.createElement('model-viewer')
player.id = "player";
player.setAttribute('src', typeof this.model === "string" ? this.model : !id && typeof this.model === "object" ? this.model[0].src : id && typeof this.model === "object" ? this.model[id].src : "")
if(!localStorage.getItem('interaction')){
player.setAttribute('reveal', "interaction")
}
player.setAttribute('environment-image', this.environement)//neutral
player.setAttribute('shadow-intensity', "0")
player.setAttribute('max-field-of-view', "150deg")
player.setAttribute('min-field-of-view', "10deg")
player.setAttribute('alt', 'modèle 3D')
player.setAttribute('bounds', 'tight')
player.setAttribute('enable-pan', true)
player.setAttribute('ar-modes', "webxr scene-viewer quick-look")
player.setAttribute('camera-controls', '')
player.setAttribute('interaction-prompt', 'none')
player.setAttribute('ar', true)
const windowWidth = (window.innerWidth * 0.0002645833).toFixed(2)
player.scale = `${windowWidth} ${windowWidth} ${windowWidth}`
const poster = document.createElement('div')
poster.id = "lazy-load-poster"
poster.slot = 'poster'
if(!localStorage.getItem('interaction')){
const loadButton = document.createElement('div')
loadButton.id = "button-load"
loadButton.slot = "poster"
loadButton.innerText = "Charger"
player.append(loadButton)
}
player.append(poster)
// if(!localStorage.getItem('interaction')){}
document.getElementById(this.parent).append(player)
this.player = player
// player.hasBakedShadow();
// this.controls();
return player;
}
/**
*
* @builds the play/pause option
*/
buildControls(){
// this.controls()
const player = this.player //document.getElementById(this.player)
const defaultAnimation = player.availableAnimations && player.availableAnimations[0] ? player.availableAnimations[0] : false;
// on vérifie d'abord qu'il y a au moins une animation
// si oui on construit sinon on ne fait rien
if(Array.from(player.availableAnimations).length > 0){
if(defaultAnimation){
player.setAttribute("animation-name", defaultAnimation)
}
const playerParent = document.createElement('div')
playerParent.id ="myProgress"
playerParent.classList.add('d-flex')
playerParent.classList.add('mt-2')
playerParent.classList.add('mx-auto')
const playBtn = document.createElement('i')
playBtn.id = "play"
playBtn.classList.add('fas')
playBtn.classList.add('fa-play-circle')
playBtn.classList.add('icones')
playBtn.title = "Lancer la lecture de l'animation"
playBtn.setAttribute("alt", "jouer l'animation")
playBtn.setAttribute('tabindex', 0)
playBtn.onclick = (e)=>{
if(player.availableAnimations && Array.from(player.availableAnimations).length >= 1){
if(playBtn.classList.contains('fa-play-circle')){
playBtn.classList.remove('fa-play-circle')
playBtn.classList.add('fa-pause-circle')
// console.log(this.player.src)
player.play({repetitions:0, pingpong:false})
console.log(this.player.src)
move(player.duration, false);
setTimeout(() => {
if(this.player.src === "modeles/Dinosaur.glb"){
const audio = new Audio('modeles/t-rex.wav')
audio.play()
}
}, 500);
}else if(playBtn.classList.contains('fa-pause-circle')){
playBtn.classList.add('fa-play-circle')
playBtn.classList.remove('fa-pause-circle')
player.pause()
move(player.duration, true);
}
}
}
if(document.activeElement === playBtn){
document.addEventListener('click', (e)=>{
if(e.keyCode === 32){
e.preventDefault()
console.log('blah')
}
})
}
const playLoop = document.createElement('i')
playLoop.classList.add('fas')
playLoop.classList.add('fa-sync-alt')
playLoop.classList.add('icones')
playLoop.setAttribute('tabindex', 0)
playLoop.setAttribute('alt', 'Jouer en continue')
playLoop.title = "Jouer en continue"
playLoop.style.backgroundColor = "rgba(0,0,0,0)"
playLoop.onclick = (e) =>{
player.play({repetitions:"infinity", pingpong:false})
// console.log(document.getElementById('play'))
const play = document.getElementById('play')
if(play.classList.contains('fa-play-circle')){
play.classList.remove('fa-play-circle')
play.classList.add('fa-pause-circle')
player.play({repetitions:"infinity", pingpong:false})
move(player.duration, false);
}
}
const bar = document.createElement('div')
bar.id="myBar"
const duration = document.createElement('div')
duration.id="duration"
duration.innerText = "0:00 / 0:00"
playerParent.append(playLoop)
playerParent.append(playBtn)
playerParent.append(bar)
// playerParent.append(cursor)
playerParent.append(duration)
player.currentTime=0.1
player.append(playerParent)
function move(time, pause) {
// console.log("temps de l'animation : "+parseInt(time))
let i = 0;
if (i == 0) {
i = 1;
const elem = bar;
let width = 0;
let id = setInterval(frame, time);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
elem.style.width = "0%"
player.currentTime=0.1;
if(playBtn.classList.contains('fa-pause-circle')){
// console.log('oui')
playBtn.classList.remove('fa-pause-circle')
playBtn.classList.add('fa-play-circle')
}
}else {
width=player.currentTime>0 ? player.currentTime*100/time : 100;
elem.style.width = width + "%";
if(document.getElementById('duration')){
document.getElementById('duration').innerText = player.currentTime.toFixed(2) + " / " + time.toFixed(2)
}
}
}
}
}
const speedSelect = document.createElement('select')
speedSelect.style.width = "75px"
speedSelect.classList.add('form-select')
let speeds = [1, 0.5, 2, 3] //, -1
speeds.map((vit)=>{
let optV = document.createElement('option')
optV.value=vit
optV.label = vit > -1 ? "X"+vit : "↶"
speedSelect.append(optV)
})
speedSelect.onchange = (e)=>{
// console.log(e.target.value)
this.player.timeScale = e.target.value
}
playerParent.prepend(speedSelect)
this.playerCtrl = playerParent
return playerParent;
}
}
buildSidebar(id){
const parent = document.getElementById(this.parent);
const modelId = id;
const player = this.player
const parts = player.model.materials;
const defaultAnimation = player.availableAnimations && player.availableAnimations[0] ? player.availableAnimations[0] : false;
const animationList = player.availableAnimations && player.availableAnimations.length > 1 ? player.availableAnimations : []
const sideBar = document.createElement('div')
sideBar.id ="champ-info_troisd"
sideBar.classList.add('text-center')
sideBar.classList.add('alert')
sideBar.classList.add('alert-primary')
const hr = document.createElement('hr')
const hideTitle = document.createElement('h5')
hideTitle.id = "hideTitle"
hideTitle.classList.add('mt-5')
hideTitle.innerText = "Montrer / cacher des éléments"
const hideSidebar = document.createElement('button')
hideSidebar.classList.add('btn')
hideSidebar.classList.add('text-white')
hideSidebar.onclick = (e) =>{
e.preventDefault()
this.sidebar.remove()
this.showSideBar();
// document.getElementById(this.parent).append(showSidebar)
}
hideSidebar.id = "hideSidebar"
// oui je sais, innerHtml c'est l'enfer qui m'attend
hideSidebar.innerHTML='<i class="fas fa-window-close" id="closeIt"></i>'
hideSidebar.setAttribute('style', 'position:absolute;right:1rem;')
const fullScreen = this.fullScreener()
sideBar.appendChild(fullScreen)
sideBar.appendChild(hideSidebar)
sideBar.append(hideTitle)
sideBar.append(hr)
if(parts.length >= 0){
//on va nester les deux boutons dans une div
const hidersDiv = document.createElement('div')
hidersDiv.classList.add('d-flex', 'justify-content-between')
const showAll = document.createElement('button')
showAll.classList.add('btn', 'btn-secondary')
showAll.innerText = "Voir tout"
showAll.setAttribute('aria-label', 'Afficher tous les éléments du modèle')
showAll.setAttribute('tabindex', '0')
showAll.onclick = (e) =>{
//hideElement
const hiders = document.getElementsByClassName('showElement')
for(let i = 0; i < hiders.length; i++){
hiders[i].click()
}
}
const hideAll = document.createElement('button')
hideAll.classList.add('btn', 'btn-secondary', 'ml-2')
hideAll.innerText = "Cacher tout"
hideAll.setAttribute('tabindex', '0')
hideAll.setAttribute('aria-label', 'Cacher tous les éléments du modèle')
hideAll.onclick = (e) =>{
//hideElement
const hiders = document.getElementsByClassName('hideElement')
for(let i = 0; i < hiders.length; i++){
hiders[i].click()
}
}
hidersDiv.append(showAll)
hidersDiv.append(hideAll)
sideBar.append(hidersDiv)
}
parts.map((part, id)=>{
const divCtrl = document.createElement('div')
divCtrl.classList.add('displayBtn')
divCtrl.classList.add('mt-1')
divCtrl.classList.add('d-flex')
const hideBtn = document.createElement('i')
hideBtn.classList.add('fas')
hideBtn.classList.add('btn')
hideBtn.classList.add('text-white')
hideBtn.classList.add('fa-eye-slash')
hideBtn.classList.add('hideElement')
hideBtn.setAttribute('data-model', id)
hideBtn.setAttribute('tabindex', 0)
hideBtn.title = "Cacher l'élément"
hideBtn.setAttribute('alt', 'Cacher l\'élément')
hideBtn.onclick = (e)=>{
parts[parseInt(e.target.getAttribute("data-model"))].setAlphaMode('MASK')
hideBtn.style.display = "none"
showBtn.style.display = "block"
setTimeout(() => {
parts[id].pbrMetallicRoughness.setBaseColorFactor([1,1,1,0]);
}, 100);
}
divCtrl.append(hideBtn)
const showBtn = document.createElement('i')
showBtn.classList.add('fas')
showBtn.classList.add('btn')
showBtn.classList.add('text-white')
showBtn.classList.add('fa-eye')
showBtn.classList.add('showElement')
showBtn.setAttribute('tabindex', 0)
showBtn.setAttribute('alt', 'cacher l\'élément')
showBtn.title = "cacher l'élément"
showBtn.setAttribute('data-model', id)
showBtn.style.display = "none"
showBtn.onclick = (e)=>{
parts[parseInt(e.target.getAttribute("data-model"))].setAlphaMode('OPAQUE')
showBtn.style.display = 'none'
hideBtn.style.display = "block"
setTimeout(() => {
parts[id].pbrMetallicRoughness.setBaseColorFactor([1,1,1,1]);
}, 100);
}
divCtrl.append(showBtn)
const colorBtn = document.createElement('i')
colorBtn.classList.add('fas')
colorBtn.classList.add('btn')
colorBtn.classList.add('text-white')
colorBtn.classList.add('fa-paint-roller')
colorBtn.setAttribute('tabindex', 0)
colorBtn.setAttribute('alt', "Changer la couleur de l'élément")
colorBtn.setAttribute('aria-label', "Changer la couleur de l'élément")
colorBtn.title = "Changer la couleur de l'élément"
colorBtn.setAttribute('data-model', id)
colorBtn.onclick = (e)=>{
const material = parts[parseInt(e.target.getAttribute("data-model"))]
material != null ? material.pbrMetallicRoughness.setBaseColorFactor([Math.random(), Math.random(), Math.random()]) : ""
}
divCtrl.append(colorBtn)
const partName = document.createElement('h5')
partName.innerText = part.name
divCtrl.append(partName)
sideBar.append(divCtrl)
})
player.append(sideBar)
this.sidebar = sideBar
if(animationList.length > 1){
// S'il y a plusieurs animation on construira un select avec leur ensemble
this.buildAnimationSelector(animationList)
}
if(this.poi){
this.hotSpotBtn(modelId);
}
if(typeof this.model === "object" && id && this.model[id].part){
// console.log(this.model[id].part)
this.movePart(this.model[id].part);
}
if(typeof this.model === "object" && this.model[0].poi && !id){
// console.log('if(typeof this.model === "object" && this.model[0].poi && !id){')
this.hotSpotBtn(modelId);
this.getOtherModel();
}else if(id && typeof this.model === "object"){
// console.log('}else if(id && typeof this.model === "object"){')
this.getOtherModel(modelId);
if(this.model[id].poi){
this.hotSpotBtn(modelId);
}
}else{
this.getOtherModel();
}
return this.sidebar;
}
buildAnimationSelector=(options)=>{
// console.log(this.sidebar)
const modelViewer = this.player
const side = document.getElementById(this.sidebar.id)
const title = document.createElement('h5')
title.classList.add('mt-5')
title.innerText = `This model possesses ${options.length} animations`
const titleAfterHr = document.createElement('hr')
const select = document.createElement('select')
select.classList.add('form-control')
// select.classList.append('form-control')
options.map((opt, id)=>{
const option = document.createElement('option')
option.value = opt
option.id = id
option.label = opt
select.append(option)
})
select.onchange = (e) =>{
modelViewer.pause()
modelViewer.animationName = e.target.value
}
side.append(title)
side.append(titleAfterHr)
side.append(select)
}
showSideBar(){
// console.log("blaah")
const showSidebarBtn = document.createElement('span')
showSidebarBtn.classList.add('btn')
showSidebarBtn.classList.add('text-white')
showSidebarBtn.onclick=(e)=>{
e.preventDefault();
this.buildSidebar();
showSidebarBtn.remove()
}
showSidebarBtn.id = "showSideBar"
showSidebarBtn.innerHTML = '<i class="fas fa-cogs" tabindex="0" id="fa-cogs"></i>'
this.cogs = showSidebarBtn;
if(document.getElementById('iconsWrapper')){
document.getElementById('iconsWrapper').append(showSidebarBtn)
}else{
document.getElementById(this.parent).append(showSidebarBtn)
}
}
hotSpotBtn(id){
const modelViewer = this.player
const json = this.poi && typeof this.model === "string" ? this.poi : typeof this.model === "object" && id ? this.model[id].poi : typeof this.model === "object" && this.model[0].poi ? this.model[0].poi : null
const sidebar = this.sidebar
const windowWidth = (window.innerWidth * 0.0002645833).toFixed(2)
const hr = document.createElement('hr')
const title = document.createElement('h5')
title.classList.add('mt-5')
title.innerText = "Voir les points d'intérêts"
const poiBtn = document.createElement('button')
poiBtn.classList.add('btn')
poiBtn.id ="poi"
poiBtn.innerText ="voir"
poiBtn.onclick = (e) =>{
e.preventDefault();
if(!this.show){
fetch(json)
.then(res=>res.json())
.then((data)=>{
const hotspots = data.hotspots
for(let i=0; i<hotspots.length; i++){
let dPositionArray = hotspots[i]["data-position"].split(' ')
let dPositionString = [];
dPositionArray.map((p)=>{
// console.log(parseFloat(p.slice(0, -1)))
let newP = (parseFloat(p.slice(0, -1)))*windowWidth
dPositionString.push(newP.toString()+"m")
})
const spot = document.createElement('button')
// spot.innerText = hotspots[i]["text"]
const nomOs = hotspots[i]["text"];
spot.classList.add('view-button')
spot.innerText = i+1
spot.setAttribute('slot', hotspots[i]["slot"])
spot.setAttribute('data-position', dPositionString.join(' ')) //hotspots[i]["data-position"]
spot.setAttribute('data-normal', hotspots[i]["data-normal"])
spot.setAttribute('data-visibility-attribute', hotspots[i]["data-visibility-attribute"])
spot.setAttribute('tabindex', "0")
spot.setAttribute('aria-label', 'Point d\'intérêt')
// spot.setAttribute('slot', hotspots[i]["slot"])
spot.onclick = (e)=>{
e.preventDefault();
// console.log(spot.dataset.normal + " :normal")
// console.log(spot.dataset.position + " :position")
const isFound = bones.some(element => {
if (element.nom.toLowerCase().replace(/\s/g, '') === nomOs.toLowerCase().replace(/\s/g, '')) {
if(element.description && element.description !== ""){
// return nomOs + "\n\r" + element.description;
Swal.fire({
title:nomOs,
text:element.description
})
}else{
Swal.fire(nomOs)
}
}
});
}
modelViewer.append(spot)
}
})
poiBtn.innerText = "Cacher"
this.show = true;
}else{
const elements = document.getElementsByClassName('view-button');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
poiBtn.innerText = "Voir"
this.show = false;
}
}
sidebar.append(title)
sidebar.append(hr)
sidebar.append(poiBtn)
}
addTextureAndColor(){
const modelViewerTexture = this.player;
const materials = modelViewerTexture.model.materials;
if(materials.length > 0){
materials.map((material)=>{
material.pbrMetallicRoughness.setBaseColorFactor([Math.random(), Math.random(), Math.random()])
material.pbrMetallicRoughness.setRoughnessFactor(1);
})
}
}
getOtherModel(){
if(this.model.length > 1){
const select = document.createElement('select')
select.classList.add('w-100')
select.classList.add('mt-5')
select.classList.add('form-control')
const models = this.model
const sideBar = this.sidebar
const choose = document.createElement('option')
choose.value = null
choose.label = "Changer de modèle"
// choose.disabled = true
select.append(choose)
models.map((model,id)=>{
const opt = document.createElement('option')
opt.id = id;
opt.value = id
opt.label = this.player.src && model.src.replace('modeles/','').replace('.glb','').split("/").pop() === this.player.src.replace('modeles/','').replace('.glb','').split("/").pop() ? model.src.replace('modeles/','').replace('.glb','').split("/").pop() + " (modèle affiché)" : model.src.replace('modeles/','').replace('.glb','').split("/").pop()
opt.disabled = this.player.src && model.src.replace('modeles/','').replace('.glb','').split("/").pop() === this.player.src.replace('modeles/','').replace('.glb','').split("/").pop() ? true : false
// opt.selected = this.player.src && model.src.replace('modeles/','').replace('.glb','').split("/").pop() === this.player.src.replace('modeles/','').replace('.glb','').split("/").pop() ? true : false
select.append(opt)
})
/**
this.player
this.playerCtrl
this.sidebar
*/
select.onchange = (e) =>{
// console.log(e.target.value)
if(e.target.value !== null){
// console.log(this.player)
const id = parseInt(e.target.value)
this.player.remove()
if(this.playerCtrl){
this.playerCtrl.remove()
}
this.sidebar.remove()
const nuovo = this.buildPlayer(id);
nuovo.addEventListener('load', ()=>{
this.buildControls();
this.buildSidebar(id);
this.multi = true;
this.controls(id)
if(document.getElementById('fa-cogs')){
document.getElementById('fa-cogs').remove()
}
if(document.getElementById('closeIt')){ //on cache le panneau d'option pour une meilleure ergonomie.
document.getElementById('closeIt').click()
}
if(document.getElementById('poiAlert3d')){
document.getElementById('poiAlert3d').style.display = "none"
}
if(playerMulti.cogs && document.getElementById('showSideBar')){
const newCog = document.getElementById('showSideBar')
document.getElementById('showSideBar').remove()
document.getElementById('iconsWrapper').append(newCog)
}
})
}
}
// on ajoute le select à la sidebar à droite
if(window.innerWidth >= 800){
sideBar.append(select)
}else{
this.player.append(select)
}
}
}
movePart = (id) =>{
const part = parseInt(id)
const modelPart = this.player
const materials = modelPart.model.materials;
// console.log(modelPart.model.materials[id])
modelPart.model.materials[id].normalTexture.position = `${150}deg ${250}deg ${250}deg`;
materials[part]. updateFraming()
}
fullScreener(){
const model = document.getElementById(this.parent)
const fsBtn = document.createElement('i')
fsBtn.classList.add('fas')
fsBtn.classList.add('fa-expand-arrows-alt')
fsBtn.classList.add('btn')
fsBtn.classList.add('btn-info')
fsBtn.classList.add('text-white')
fsBtn.setAttribute('tabindex', 0)
fsBtn.title = "Plein écran"
fsBtn.setAttribute('alt', 'Plein écran')
// fsBtn.classList.add('icones')
fsBtn.setAttribute('style', 'position:absolute;left:1rem;')
fsBtn.onclick = (e) =>{
e.preventDefault()
if (document.fullscreenElement) {
document.exitFullscreen()
}else{
model.requestFullscreen();
}
}
return fsBtn
}
// Gestion des contrôles clavier / souris + modale explicative
controls(id){
const modelViewer = document.querySelector("#player");
const parts = player.model.materials;
const json = this.poi && typeof this.model === "string" ? this.poi : typeof this.model === "object" && id ? this.model[id].poi : typeof this.model === "object" && this.model[0].poi ? this.model[0].poi : null
// on va mettre les icones dans un conteneur flex et colonne. Comme on va le prepend il sera à gauche
const cogs = this.cogs ? this.cogs : null
const iconsWrapper = document.createElement('div')
iconsWrapper.id = "iconsWrapper"
iconsWrapper.classList.add('d-flex', 'flex-column')
iconsWrapper.style.maxWidth = "2rem"
iconsWrapper.style.position = "absolute"
const questionMark = document.createElement('i')
questionMark.classList.add('fa-solid', 'fa-circle-question', 'mb-4')
questionMark.setAttribute('aria-label', 'Voir les commandes au clavier')
questionMark.setAttribute('tabindex', '0')
questionMark.style.fontSize = "1.5rem"
questionMark.style.borderRadius = "50%"
questionMark.style.cursor = "pointer"
questionMark.onclick = (e) =>{
e.preventDefault() //peut sembler inutile mais des fois model viewer crois que le click est pour lui (dunno why though^^)
Swal.fire({
title:"Contrôles",
html:'<div class="alert-danger"><strong>Attention !</strong><br /><span>S\'il y a des points d\'intérêts affichés, ils ne suivront pas les mouvements du modèle</span></div>'+
'<div class="mt-1" style="text-align:left !important;"><img src="../../wp-content/themes/animalia/img/32041.png" width="50px"></img>Orienter le modèle (maintenir)</div>'+
'<div class="mt-1" style="text-align:left !important;"><img src="../../wp-content/themes/animalia/img/31532.png" width="50px"></img>Déplacer le modèle (maintenir)</div>'+
'<div class="mt-1" style="text-align:left !important;"><img src="../../wp-content/themes/animalia/img/32041-double.png" width="50px"></img>Recentrer le modèle (double clique rapide)</div>'+
'<div class="mt-1" style="text-align:left !important;"><img src="../../wp-content/themes/animalia/img/32041-both.png" width="50px"></img>Changer l\'axe de rotation (simple clique)</div>'+
'<p class="text-center h3">Raccourcis clavier<p>'+
'<div class="mt-1" style="text-align:left !important;"><i class="fa-solid fa-keyboard"></i> (touche 2/4/6/7/8/9) Orienter le modèle</div>'+
'<div class="mt-1" style="text-align:left !important;"><i class="fa-solid fa-keyboard"></i> (touche 5) Recentrer le modèle</div>'+
'<div class="mt-1" style="text-align:left !important;"><i class="fa-solid fa-keyboard"></i> (touche +/-) Zoomer / Dézoomer</div>'+
'<div class="mt-1" style="text-align:left !important;"><i class="fa-solid fa-keyboard"></i> (touche 0/1) Luminosité (↓/↑)</div>'
// '<div class="mt-1" style="text-align:left !important;"><i class="fa-solid fa-keyboard"></i> (espace) Play / Pause</div>'
})
}
const fullScreen = document.createElement('i')
fullScreen.classList.add('fas', 'fa-expand-arrows-alt', 'mb-4', "rounded")
fullScreen.setAttribute('aria-label', "plein écran")
fullScreen.setAttribute('tabindex', "0")
fullScreen.style.fontSize = "1.5rem"
fullScreen.style.borderRadius = "50%"
fullScreen.style.cursor = "pointer"
fullScreen.onclick = e =>{
if (document.fullscreenElement) {
document.exitFullscreen()
}else{
modelViewer.requestFullscreen();
}
}
// hideall
const hideAll = document.createElement('i')
hideAll.classList.add('fas', 'fa-eye-slash', "rounded")
hideAll.style.fontSize = "1.5rem"
hideAll.style.borderRadius = "50%"
hideAll.style.cursor = "pointer"
hideAll.setAttribute('aria-label', 'Cacher et voir tout le model')
hideAll.setAttribute('tab-index', '0')
hideAll.onclick = e =>{
if(hideAll.classList.contains('fa-eye-slash')){
hideAll.classList.remove('fa-eye-slash')
hideAll.classList.add('fa-eye')
parts.map((part)=>{
part.setAlphaMode('MASK')
part.pbrMetallicRoughness.setBaseColorFactor([1,1,1,0]);
})
}else if(hideAll.classList.contains('fa-eye')){
hideAll.classList.remove('fa-eye')
hideAll.classList.add('fa-eye-slash')
parts.map((part)=>{
part.setAlphaMode('OPAQUE')
part.pbrMetallicRoughness.setBaseColorFactor([1,1,1,1]);
})
}
}
let poiBtn = null
if(json){
// console.log(this.poi)
hideAll.classList.add("mb-4")
poiBtn = document.createElement('i')
poiBtn.classList.add('fas', 'fa-map-marked-alt', "mb-4")
poiBtn.setAttribute('tabindex', '0')
poiBtn.style.cursor = 'pointer'
poiBtn.style.fontSize = "1.5rem"
const windowWidth = (window.innerWidth * 0.0002645833).toFixed(2)
poiBtn.onclick = e =>{
if(!this.show){
fetch(json)
.then(res=>res.json())
.then((data)=>{
const hotspots = data.hotspots
for(let i=0; i<hotspots.length; i++){
let dPositionArray = hotspots[i]["data-position"].split(' ')
let dPositionString = [];
dPositionArray.map((p)=>{
// console.log(parseFloat(p.slice(0, -1)))
let newP = (parseFloat(p.slice(0, -1)))*windowWidth
dPositionString.push(newP.toString()+"m")
})
// console.log(hotspots[i]["data-position"].split(' '))
// console.log(dPositionString.join(' '))
const spot = document.createElement('button')
const nomOs = hotspots[i]["text"];
spot.classList.add('view-button')
spot.innerText = i+1
spot.setAttribute('slot', hotspots[i]["slot"])
// spot.setAttribute('data-position', hotspots[i]["data-position"])
spot.setAttribute('data-position', dPositionString.join(' '))
spot.setAttribute('data-normal', hotspots[i]["data-normal"])
spot.setAttribute('data-visibility-attribute', hotspots[i]["data-visibility-attribute"])
spot.setAttribute('tabindex', "0")
spot.setAttribute('aria-label', 'Point d\'intérêt')
spot.onclick = (e)=>{
e.preventDefault();
const isFound = bones.some(element => {
if (element.nom.toLowerCase().replace(/\s/g, '') === nomOs.toLowerCase().replace(/\s/g, '')) {
if(element.description && element.description !== ""){
Swal.fire({
title:nomOs,
text:element.description,
target:this.player
})
}else{
Swal.fire({
text:nomOs,
target:this.player
})
}
}
});
}
modelViewer.append(spot)
}
})
// poiBtn.innerText = "Cacher"
this.show = true;
}else{
const elements = document.getElementsByClassName('view-button');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
// poiBtn.innerText = "Voir"
this.show = false;
}
}
}
// hideAll.style.background = "linear-gradient(#436fb5, #508dbb, #58a3ac, #62b997)"
// generation d'une icône pour recentrer le modèle. Comportements "étranges"
const bullsEye = document.createElement('i')
bullsEye.classList.add('fa', 'fa-bullseye', "rounded", 'mt-2', 'mb-4')
bullsEye.style.fontSize = "1.5rem"
bullsEye.style.borderRadius = "50%"
bullsEye.style.cursor = "pointer"
bullsEye.setAttribute('title', 'recentrer le modèle')
bullsEye.setAttribute('aria-label', 'recentrer le modèle')
bullsEye.setAttribute('tab-index', '0')
bullsEye.onclick = e =>{
modelViewer.updateFraming()
}
const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
const brush = document.createElement('i')
brush.classList.add('fas', 'fa-paint-roller', "rounded", 'mt-2', 'mb-4')
brush.style.fontSize = "1.5rem"
brush.style.borderRadius = "50%"
brush.style.cursor = "pointer"
brush.setAttribute('title', 'Peindre les éléments')
brush.setAttribute('aria-label', 'Peindre les éléments')
brush.setAttribute('tab-index', '0')
brush.onclick = e =>{
const parts = player.model.materials;
parts.map(part=>{
part.pbrMetallicRoughness.setBaseColorFactor([Math.random(), Math.random(), Math.random()])
})
}
iconsWrapper.append(questionMark)
iconsWrapper.append(fullScreen)
iconsWrapper.append(hideAll)
iconsWrapper.append(bullsEye)
if(poiBtn){
// console.log(poiBtn)
iconsWrapper.append(poiBtn)
}
iconsWrapper.append(brush)
if(cogs){
console.log(cogs)
iconsWrapper.append(cogs)
}
modelViewer.appendChild(iconsWrapper)
const tapDistance = 2;
let panning = false;
let panX, panY;
let startX, startY;
let lastX, lastY;
let metersPerPixel;
const startPan = () => {
const orbit = modelViewer.getCameraOrbit();
const {theta, phi, radius} = orbit;
const psi = theta - modelViewer.turntableRotation;
metersPerPixel = 0.75 * radius / modelViewer.getBoundingClientRect().height;
panX = [-Math.cos(psi), 0, Math.sin(psi)];
panY = [
-Math.cos(phi) * Math.sin(psi),
Math.sin(phi),
-Math.cos(phi) * Math.cos(psi)
];
modelViewer.interactionPrompt = 'none';
};
const stopPan = (event) => {
panning = false;
}
const movePan = (thisX, thisY) => {
const dx = (thisX - lastX) * metersPerPixel;
const dy = (thisY - lastY) * metersPerPixel;
lastX = thisX;
lastY = thisY;
const target = modelViewer.getCameraTarget();
target.x += dx * panX[0] + dy * panY[0];
target.y += dx * panX[1] + dy * panY[1];
target.z += dx * panX[2] + dy * panY[2];
modelViewer.cameraTarget = `${target.x}m ${target.y}m ${target.z}m`;
// This pauses turntable rotation
modelViewer.dispatchEvent(new CustomEvent(
'camera-change', {detail: {source: 'user-interaction'}}));
};
const recenter = (pointer) => {
panning = false;
if (Math.abs(pointer.clientX - startX) > tapDistance ||
Math.abs(pointer.clientY - startY) > tapDistance)
return;
const hit = modelViewer.positionAndNormalFromPoint(pointer.clientX, pointer.clientY);
if(hit != null) {
modelViewer.cameraTarget = hit.position.toString();
}
else {
modelViewer.cameraTarget = 'auto auto auto';
modelViewer.cameraOrbit = 'auto auto auto';
}
};
modelViewer.addEventListener('mousedown', (event) => {
startX = event.clientX;
startY = event.clientY;
panning = event.button === 2 || event.ctrlKey || event.metaKey ||
event.shiftKey;
if (!panning)
return;
lastX = startX;
lastY = startY;
startPan();
event.stopPropagation();
}, true);
modelViewer.addEventListener('touchstart', (event) => {
const {targetTouches, touches} = event;
startX = targetTouches[0].clientX;
startY = targetTouches[0].clientY;
panning = targetTouches.length === 2 && targetTouches.length === touches.length;
if (!panning)
return;
lastX = 0.5 * (targetTouches[0].clientX + targetTouches[1].clientX);
lastY = 0.5 * (targetTouches[0].clientY + targetTouches[1].clientY);
startPan();
}, true);
self.addEventListener('mousemove', (event) => {
if (!panning)
return;
movePan(event.clientX, event.clientY);
event.stopPropagation();
}, true);
modelViewer.addEventListener('touchmove', (event) => {
if (!panning || event.targetTouches.length !== 2)
return;
const {targetTouches} = event;
const thisX = 0.5 * (targetTouches[0].clientX + targetTouches[1].clientX);
const thisY = 0.5 * (targetTouches[0].clientY + targetTouches[1].clientY);
movePan(thisX, thisY);
}, true);
let lastMousedown = {time: new Date().getTime()};
let lastTouchstart = {time: new Date().getTime()};
function doubletap(timer) {
var now = new Date().getTime();
var timesince = now - timer.time;
timer.time = new Date().getTime();
if((timesince < 400) && (timesince > 0))
return true;
else
return false;
}
self.addEventListener('mouseup', (event) => {
stopPan(event);
}, true);
modelViewer.addEventListener('oncontextmenu', (event) => {
return false;
});
self.addEventListener('mousedown', (event) => {
if(doubletap(lastMousedown))
recenter(event);
}, true);
modelViewer.addEventListener('touchstart', (event) => {
if (doubletap(lastTouchstart) && event.targetTouches.length === 0) {
recenter(event.changedTouches[0]);
if (event.cancelable) {
event.preventDefault();
}
}
}, true);
const nuovo = document.getElementById('player')
let x = this.x
let y = this.y
let z = this.z
let fieldOfView = 50