forked from cyberbotics/webots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviewer.js
1506 lines (1331 loc) · 50.2 KB
/
viewer.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
/* eslint no-extend-native: ["error", { "exceptions": ["String"] }] */
/* global getGETQueryValue */
/* global getGETQueriesMatchingRegularExpression */
/* global setup */
/* global showdown */
/* global hljs */
/* global THREE */
/* global webots */
/* exported resetRobotComponent */
/* exported toggleDeviceComponent */
/* exported highlightX3DElement */
/* exported openTabFromEvent */
'use strict';
var handle;
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function(prefix) {
return this.slice(0, prefix.length) === prefix;
};
}
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
function isInternetExplorer() {
var userAgent = navigator.userAgent;
return userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident') !== -1;
};
var localSetup = (typeof setup === 'undefined') ? {} : setup;
var isCyberboticsUrl = location.href.indexOf('cyberbotics.com/doc') !== -1;
function setupCyberboticsUrl(url) {
localSetup.book = 'guide';
localSetup.page = 'index';
localSetup.anchor = '';
if (!localSetup.tabs)
localSetup.tabs = {};
var m = url.match(new RegExp('/([^/]+)/([^/\\?#]+)([^/]*)$'));
if (m) {
localSetup.book = m[1];
localSetup.page = m[2];
var args = m[3];
m = url.match(/version=([^&#]*)/);
if (m) {
var version = m[1];
var n = version.indexOf(':');
if (n === -1)
localSetup.branch = version;
else
localSetup.branch = version.substr(n + 1);
}
// Extract tab options
var tabRegex = /[?&](tab-[^=]+)=([^&#]+)/g;
while ((m = tabRegex.exec(url)) !== null)
localSetup.tabs[m[1]] = m[2];
m = args.match(/#([^&#]*)/);
if (m)
localSetup.anchor = m[1];
else
localSetup.anchor = '';
}
}
function setupDefaultUrl(url) {
var m;
m = url.match(/page=([^&#]*)/);
if (m)
localSetup.page = m[1].replace(/.md$/, '');
else
localSetup.page = 'index';
m = url.match(/book=([^&#]*)/);
if (m)
localSetup.book = m[1];
else if (!localSetup.book)
localSetup.book = 'guide';
// Extract tab options
if (!localSetup.tabs)
localSetup.tabs = {};
var tabRegex = /[?&](tab-[^=]+)=([^&#]+)/g;
while ((m = tabRegex.exec(url)) !== null)
localSetup.tabs[m[1]] = m[2];
m = url.match(/#([^&#]*)/);
if (m)
localSetup.anchor = m[1];
else
localSetup.anchor = '';
}
function setupUrl(url) {
if (isCyberboticsUrl)
setupCyberboticsUrl(url);
else
setupDefaultUrl(url);
var tabsQuery = '';
for (var option in localSetup.tabs) {
if (!localSetup.tabs[option])
continue;
if (tabsQuery)
tabsQuery += ',';
tabsQuery += option + '=' + localSetup.tabs[option];
}
tabsQuery = '[' + tabsQuery + ']';
console.log('book=' + localSetup.book + ' page=' + localSetup.page + ' branch=' + localSetup.branch + ' tabs=' + tabsQuery + ' anchor=' + localSetup.anchor);
}
function computeTargetPath() {
var branch = 'master';
var targetPath = '';
if (localSetup.branch)
branch = localSetup.branch;
if (localSetup.url.startsWith('http'))
targetPath = localSetup.url + branch + '/docs/';
targetPath += localSetup.book + '/';
return targetPath;
}
function redirectUrls(node) {
// redirect a's href
var as = node.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
var a = as[i];
var href = a.getAttribute('href');
if (!href)
continue;
else if (href.startsWith('#'))
addDynamicAnchorEvent(a); // on firefox, the second click on the anchor is not dealt cleanly
else if (href.startsWith('http')) // open external links in a new window
a.setAttribute('target', '_blank');
else if (href.endsWith('.md') || href.indexOf('.md#') > -1) {
var match, newPage, anchor;
if (href.startsWith('../')) { // Cross-book hyperlink case.
match = /^..\/([\w-]+)\/([\w-]+).md(#[\w-]+)?$/.exec(href);
if (match && match.length >= 3) {
var book = match[1];
newPage = match[2];
anchor = match[3];
if (anchor)
anchor = anchor.substring(1); // remove the '#' character
a.setAttribute('href', forgeUrl(book, newPage, localSetup.tabs, anchor));
}
} else { // Cross-page hyperlink case.
addDynamicLoadEvent(a);
match = /^([\w-]+).md(#[\w-]+)?$/.exec(href);
if (match && match.length >= 2) {
newPage = match[1];
anchor = match[2];
if (anchor)
anchor = anchor.substring(1); // remove the '#' character
a.setAttribute('href', forgeUrl(localSetup.book, newPage, localSetup.tabs, anchor));
}
}
}
}
}
function collapseMovies(node) {
if (location.href.startsWith('file:')) { // if it's the offline documentation embedded in Webots (possibly without network):
var iframes = node.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) { // foreach iframe:
var iframe = iframes[i];
var src = iframe.getAttribute('src');
if (src && src.indexOf('youtube')) { // if the iframe is a youtube frame:
// then, replace the iframe by a text and an hyperlink to the youtube page.
src = src.replace(/embed\/(.*)\?rel=0/, 'watch?v=$1'); // e.g. https://www.youtube.com/embed/vFwNwT8dZTU?rel=0 to https://www.youtube.com/watch?v=vFwNwT8dZTU
var p = document.createElement('p');
p.innerHTML = '<a href="' + src + '">Click here to see the youtube movie.</a>';
iframe.parentNode.replaceChild(p, iframe);
}
}
}
}
function forgeUrl(book, page, tabs, anchor) {
var tabOption;
var isFirstArgument;
var anchorString = (anchor && anchor.length > 0) ? ('#' + anchor) : '';
var url = location.href;
if (isCyberboticsUrl) {
var i = location.href.indexOf('cyberbotics.com/doc');
url = location.href.substr(0, i) + 'cyberbotics.com/doc/' + book + '/' + page;
if (localSetup.branch !== '' && localSetup.repository && localSetup.repository !== 'cyberbotics')
url += '?version=' + localSetup.repository + ':' + localSetup.branch;
else if (localSetup.branch !== '')
url += '?version=' + localSetup.branch;
isFirstArgument = localSetup.branch === '';
for (tabOption in tabs) {
if (!tabs[tabOption])
continue;
url += (isFirstArgument ? '?' : '&') + tabOption + '=' + tabs[tabOption];
isFirstArgument = false;
}
url += anchorString;
} else {
isFirstArgument = (url.indexOf('?') < 0);
// Remove anchor from url
url = url.split('#')[0];
// Add or replace the book argument.
if (url.indexOf('book=') > -1)
url = url.replace(/book=([^&]+)?/, 'book=' + book);
else
url += (isFirstArgument ? '?' : '&') + 'book=' + book;
// Add or replace the page argument.
if (url.indexOf('page=') > -1)
url = url.replace(/page=([\w-]+)?/, 'page=' + page);
else
url += (isFirstArgument ? '?' : '&') + 'page=' + page;
// Add or replace the tab argument.
for (tabOption in tabs) {
let tabName = tabs[tabOption] ? tabs[tabOption] : '';
if (url.indexOf(tabOption + '=') > -1)
url = url.replace(new RegExp(tabOption + '=([^&]+)(#[\\w-]+)?'), tabOption + '=' + tabName);
else if (tabName)
url += (isFirstArgument ? '?' : '&') + tabOption + '=' + tabName;
}
url += anchorString;
}
return url;
}
function addDynamicAnchorEvent(el) {
if (el.classList.contains('dynamicAnchor'))
return;
el.addEventListener('click',
function(event) {
var node = event.target;
while (node && !node.hasAttribute('href'))
node = node.getParent();
if (node) {
localSetup.anchor = extractAnchor(node.getAttribute('href'));
applyAnchor();
event.preventDefault();
}
},
false
);
el.classList.add('dynamicAnchor');
}
function addDynamicLoadEvent(el) {
if (el.classList.contains('dynamicLoad'))
return;
el.addEventListener('click',
function(event) {
aClick(event.target);
event.preventDefault();
},
false
);
el.classList.add('dynamicLoad');
}
function aClick(el) {
setupUrl(el.getAttribute('href'));
getMDFile();
updateBrowserUrl();
updateContributionBannerUrl();
}
function redirectImages(node) {
// redirect img's src
var imgs = node.querySelectorAll('img');
var targetPath = computeTargetPath();
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
var src = img.getAttribute('src');
var match = /^images\/(.*)$/.exec(src);
if (match && match.length === 2)
img.setAttribute('src', targetPath + 'images/' + match[1]);
}
}
function setupModalWindow() {
var doc = document.querySelector('#webots-doc');
// Create the following HTML tags:
// <div id="modal-window" class="modal-window">
// <span class="modal-window-close-button">×</span>
// <img class="modal-window-image-content" />
// <div class="modal-window-caption"></div>
// </div>
var close = document.createElement('span');
close.classList.add('modal-window-close-button');
close.innerHTML = '×';
close.onclick = function() {
modal.style.display = 'none';
};
var loadImage = document.createElement('img');
loadImage.classList.add('modal-window-load-image');
loadImage.setAttribute('src', computeTargetPath() + '../css/images/load_animation.gif');
var image = document.createElement('img');
image.classList.add('modal-window-image-content');
var caption = document.createElement('div');
caption.classList.add('modal-window-caption');
var modal = document.createElement('div');
modal.setAttribute('id', 'modal-window');
modal.classList.add('modal-window');
modal.appendChild(close);
modal.appendChild(loadImage);
modal.appendChild(image);
modal.appendChild(caption);
doc.appendChild(modal);
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = 'none';
loadImage.style.display = 'block';
image.style.display = 'none';
}
};
}
function updateModalEvents(view) {
var modal = document.querySelector('#modal-window');
var image = modal.querySelector('.modal-window-image-content');
var loadImage = modal.querySelector('.modal-window-load-image');
var caption = modal.querySelector('.modal-window-caption');
// Add the modal events on each image.
var imgs = view.querySelectorAll('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = function(event) {
var img = event.target;
// The modal window is only enabled on big enough images and on thumbnail.
if (img.src.indexOf('thumbnail') === -1 && !(img.naturalWidth > 128 && img.naturalHeight > 128))
return;
// Show the modal window and the caption.
modal.style.display = 'block';
caption.innerHTML = (typeof this.parentNode.childNodes[1] !== 'undefined') ? this.parentNode.childNodes[1].innerHTML : '';
if (img.src.indexOf('.thumbnail.') === -1) {
// this is not a thumbnail => show the image directly.
image.src = img.src;
loadImage.style.display = 'none';
image.style.display = 'block';
} else {
// this is a thumbnail => load the actual image.
var url = img.src.replace('.thumbnail.', '.');
if (image.src === url) {
// The image has already been loaded.
loadImage.style.display = 'none';
image.style.display = 'block';
return;
} else {
// The image has to be loaded: show the loading image.
loadImage.style.display = 'block';
image.style.display = 'none';
}
// In case of thumbnail, search for the original png or jpg
image.onload = function() {
// The original image has been loaded successfully => show it.
loadImage.style.display = 'none';
image.style.display = 'block';
};
image.onerror = function() {
// The original image has not been loaded successfully => try to change the extension and reload it.
image.onerror = function() {
// The original image has not been loaded successfully => abort.
modal.style.display = 'none';
loadImage.style.display = 'block';
image.style.display = 'none';
};
url = img.src.replace('.thumbnail.jpg', '.png');
image.src = url;
};
image.src = url;
}
};
}
}
function applyAnchor() {
var firstAnchor = document.querySelector("[name='" + localSetup.anchor + "']");
if (firstAnchor) {
firstAnchor.scrollIntoView(true);
if (document.querySelector('.contribution-banner'))
window.scrollBy(0, -38); // GitHub banner.
if (isCyberboticsUrl)
window.scrollBy(0, -44); // Cyberbotics header.
} else
window.scrollTo(0, 0);
}
function applyToTitleDiv() {
var titleContentElement = document.querySelector('#title-content');
if (titleContentElement) {
var newTitle;
if (localSetup.book === 'guide')
newTitle = 'Webots User Guide';
else if (localSetup.book === 'reference')
newTitle = 'Webots Reference Manual';
else if (localSetup.book === 'blog')
newTitle = 'Webots Blog';
else if (localSetup.book === 'discord')
newTitle = 'Webots Discord Archives';
else if (localSetup.book === 'automobile')
newTitle = 'Webots for automobiles';
else
newTitle = '';
if (newTitle.length > 0) {
newTitle += " <div class='release-tag'>" + getWebotsVersion() + '</div>';
titleContentElement.innerHTML = newTitle;
}
}
}
function addContributionBanner() {
// if we're on the website we need to move the banner down by the height of the navbar
var displacement = isCyberboticsUrl ? '44px' : '0px';
// append contribution sticker to primary doc element
document.querySelector('#center').innerHTML += '<div style="top:' + displacement + '" class="contribution-banner">' +
'Found an error?' +
'<a target="_blank" class="contribution-banner-url" href="https://github.com/cyberbotics/webots/tree/master/docs"> ' +
'Contribute on GitHub!' +
'<span class=github-logo />' +
'</a>' +
'<p id="contribution-close">X</p>' +
'</div>';
updateContributionBannerUrl();
var contributionBanner = document.querySelector('.contribution-banner');
document.querySelector('#contribution-close').onclick = function() {
contributionBanner.parentNode.removeChild(contributionBanner);
};
}
function updateContributionBannerUrl() {
var contributionBanner = document.querySelector('.contribution-banner-url');
if (contributionBanner)
contributionBanner.href = 'https://github.com/cyberbotics/webots/edit/master/docs/' + localSetup.book + '/' + localSetup.page + '.md';
}
function addNavigationToBlogIfNeeded() {
if (!document.querySelector('#next-previous-section') && localSetup.book === 'blog') {
let menu = document.querySelector('#menu');
let lis = menu.querySelectorAll('li');
let currentPageIndex = -1;
for (let i = 0; i < lis.length; ++i) {
if (lis[i].className === 'selected') {
currentPageIndex = i;
break;
}
}
if (currentPageIndex === -1)
return;
// console.log(currentPageIndex, lis.length);
// console.log(lis);
let div = document.createElement('div');
div.setAttribute('id', 'next-previous-section');
// previous post
if (currentPageIndex > 0) {
let previous = lis[currentPageIndex - 1];
let a = previous.firstChild.cloneNode();
a.innerHTML += '<< Previous Post: ' + previous.textContent;
a.setAttribute('class', 'post-selector left');
div.appendChild(a);
}
if (currentPageIndex < lis.length - 1) {
let next = lis[currentPageIndex + 1];
let a = next.firstChild.cloneNode();
a.innerHTML += 'Next Post: ' + next.textContent + ' >>';
a.setAttribute('class', 'post-selector right');
div.appendChild(a);
}
document.querySelector('#publish-data').parentNode.insertBefore(div, document.querySelector('#publish-data').nextSibling);
}
}
function setupBlogFunctionalitiesIfNeeded() {
if (localSetup.book === 'blog') {
// hide index, this doesn't make sense for a blog post
let index = document.querySelector('#index');
let indexTitle = document.querySelector('#indexTitle');
if (index !== null)
index.style.display = 'none';
if (indexTitle !== null)
indexTitle.style.display = 'none';
// hide the release tag, this is also nonsensical here
document.querySelector('.release-tag').style.display = 'none';
document.title = document.title.replace('documentation', 'Blog');
}
}
function createIndex(view) {
// Note: the previous index is cleaned up when the parent title is destroyed.
// Get all the view headings.
var headings = [].slice.call(view.querySelectorAll('h1, h2, h3, h4'));
// Do not create too small indexes.
var content = document.querySelector('#content');
if ((content.offsetHeight < 2 * window.innerHeight || headings.length < 4) && localSetup.book !== 'discord')
return;
var level = parseInt(headings[0].tagName[1]) + 1; // current heading level.
// Create an empty index, and insert it before the second heading.
var indexTitle = document.createElement('h' + level);
indexTitle.textContent = 'Index';
indexTitle.setAttribute('id', 'indexTitle');
headings[0].parentNode.insertBefore(indexTitle, headings[1]);
var ul = document.createElement('ul');
ul.setAttribute('id', 'index');
headings[0].parentNode.insertBefore(ul, headings[1]);
headings.forEach(function(heading, i) {
if (i === 0) // Skip the first heading.
return;
// Update current level and ul.
var newLevel = parseInt(heading.tagName[1]);
while (newLevel > level) {
var newUl = document.createElement('ul');
ul.appendChild(newUl);
ul = newUl;
level += 1;
}
while (newLevel < level) {
ul = ul.parentNode;
level -= 1;
}
// Add the <li> tag.
var anchor = heading.getAttribute('name');
var a = document.createElement('a');
a.setAttribute('href', '#' + anchor);
a.textContent = heading.textContent;
var li = document.createElement('li');
li.appendChild(a);
ul.appendChild(li);
});
}
function getWebotsVersion() {
if (localSetup.branch)
return localSetup.branch;
// Get the Webots version from the showdown wbVariables extension
var version = '{{ webots.version.full }}';
var converter = new showdown.Converter({extensions: ['wbVariables']});
var html = converter.makeHtml(version);
var tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || '';
}
function applyToPageTitle(mdContent) {
var hashtagIndex = mdContent.indexOf('#');
if (hashtagIndex >= 0) {
while (hashtagIndex + 1 < mdContent.length && mdContent[hashtagIndex + 1] === '#')
hashtagIndex += 1;
var hashtagCarriageReturn = mdContent.indexOf('\n', hashtagIndex);
if (hashtagCarriageReturn >= 0) {
var title = mdContent.substring(hashtagIndex + 1, hashtagCarriageReturn).trim();
document.title = 'Webots documentation: ' + title;
}
}
}
function populateViewDiv(mdContent) {
setupUrl(document.location.href);
var view = document.querySelector('#view');
while (view.firstChild)
view.removeChild(view.firstChild);
// console.log('Raw MD content:\n\n');
// console.log(mdContent);
applyToPageTitle(mdContent);
// markdown to html
window.mermaidGraphCounter = 0;
window.mermaidGraphs = {};
var converter = new showdown.Converter({tables: 'True', extensions: ['wbTabComponent', 'wbRobotComponent', 'wbSpoiler', 'wbChart', 'wbVariables', 'wbAPI', 'wbFigure', 'wbAnchors', 'wbIllustratedSection', 'youtube']});
var html = converter.makeHtml(mdContent);
// console.log('HTML content: \n\n')
// console.log(html);
view.innerHTML = html;
createRobotComponent(view);
renderGraphs();
redirectImages(view);
updateModalEvents(view);
redirectUrls(view);
collapseMovies(view);
applyAnchorIcons(view);
highlightCode(view);
updateSelection();
createIndex(view);
setupBlogFunctionalitiesIfNeeded();
addNavigationToBlogIfNeeded();
var images = view.querySelectorAll('img');
if (images.length > 0) {
// apply the anchor only when the images are loaded,
// otherwise, the anchor can be overestimated.
var lastImage = images[images.length - 1];
$(lastImage).load(applyAnchor);
} else
applyAnchor();
applyTabs();
}
// replace the browser URL after a dynamic load
function updateBrowserUrl() {
var url = forgeUrl(localSetup.book, localSetup.page, localSetup.tabs, localSetup.anchor);
if (history.pushState) {
try {
history.pushState({state: 'new'}, null, url);
} catch (err) {
}
}
var canonicalUrl = 'https://cyberbotics.com/doc/' + localSetup.book + '/' + localSetup.page;
$('link[rel="canonical"]').attr('href', canonicalUrl);
}
// Make in order that the back button is working correctly
window.onpopstate = function(event) {
setupUrl(document.location.href);
getMDFile();
};
function highlightCode(view) {
var supportedLanguages = ['c', 'cpp', 'java', 'python', 'matlab', 'sh', 'ini', 'tex', 'makefile', 'lua', 'xml'];
for (var i = 0; i < supportedLanguages.length; i++) {
var language = supportedLanguages[i];
hljs.configure({languages: [ language ]});
var codes = document.querySelectorAll('.' + language);
for (var j = 0; j < codes.length; j++) {
var code = codes[j];
hljs.highlightBlock(code);
}
}
}
function resetRobotComponent(robot) {
unhighlightX3DElement(robot);
var robotComponent = getRobotComponentByRobotName(robot);
// Reset the Viewpoint
var camera = robotComponent.webotsView.x3dScene.getCamera();
camera.position.copy(camera.userData.initialPosition);
camera.quaternion.copy(camera.userData.initialQuaternion);
// Reset the motor sliders.
var sliders = robotComponent.querySelectorAll('.motor-slider');
for (var s = 0; s < sliders.length; s++) {
var slider = sliders[s];
slider.value = slider.getAttribute('webots-position');
var id = slider.getAttribute('webots-transform-id');
sliderMotorCallback(robotComponent.webotsView.x3dScene.getObjectById(id, true), slider);
}
robotComponent.webotsView.x3dScene.render();
}
function updateRobotComponentDimension(robot) {
var robotComponent = getRobotComponentByRobotName(robot);
var deviceMenu = robotComponent.querySelector('.device-component');
var robotView = robotComponent.querySelector('.robot-view');
if (typeof robotComponent.showDeviceComponent === 'undefined')
robotComponent.showDeviceComponent = true;
if (robotComponent.showDeviceComponent === true) {
deviceMenu.style.display = '';
robotView.style.width = '70%';
} else {
deviceMenu.style.display = 'none';
robotView.style.width = '100%';
}
robotComponent.webotsView.x3dScene.resize();
}
function toggleDeviceComponent(robot) {
var robotComponent = getRobotComponentByRobotName(robot);
if (typeof robotComponent.showDeviceComponent === 'undefined')
robotComponent.showDeviceComponent = true;
robotComponent.showDeviceComponent = !robotComponent.showDeviceComponent;
updateRobotComponentDimension(robot);
}
function toogleRobotComponentFullScreen(robot) { // eslint-disable-line no-unused-vars
// Source: https://stackoverflow.com/questions/7130397/how-do-i-make-a-div-full-screen
var element = getRobotComponentByRobotName(robot);
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
if (document.exitFullscreen)
document.exitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
} else {
if (element.requestFullscreen) {
element.requestFullscreen();
document.addEventListener('fullscreenchange', function() {
updateRobotComponentDimension(robot);
});
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
document.addEventListener('mozfullscreenchange', function() {
updateRobotComponentDimension(robot);
});
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
document.addEventListener('webkitfullscreenchange', function() {
updateRobotComponentDimension(robot);
});
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
document.addEventListener('msfullscreenchange', function() {
updateRobotComponentDimension(robot);
});
}
}
}
function sliderMotorCallback(transform, slider) {
if (typeof transform === 'undefined')
return;
if (typeof transform.firstRotation === 'undefined' && typeof transform.quaternion !== 'undefined')
transform.firstRotation = transform.quaternion.clone();
var axis = slider.getAttribute('webots-axis').split(/[\s,]+/);
axis = new THREE.Vector3(parseFloat(axis[0]), parseFloat(axis[1]), parseFloat(axis[2]));
var value = parseFloat(slider.value);
var position = parseFloat(slider.getAttribute('webots-position'));
if (slider.getAttribute('webots-type') === 'LinearMotor') {
// Compute translation
var translation = new THREE.Vector3();
if ('initialTranslation' in transform.userData)
translation = transform.userData.initialTranslation.clone();
else {
translation = transform.position;
transform.userData.initialTranslation = translation.clone();
}
translation = translation.add(axis.multiplyScalar(value - position));
// Apply the new position.
transform.position.copy(translation);
transform.updateMatrix();
} else {
// Compute angle.
var angle = value - position;
// Apply the new axis-angle.
var q = new THREE.Quaternion();
q.setFromAxisAngle(
axis,
angle
);
if (typeof transform.firstRotation !== 'undefined')
q.multiply(transform.firstRotation);
transform.quaternion.copy(q);
transform.updateMatrix();
}
}
function unhighlightX3DElement(robot) {
var robotComponent = getRobotComponentByRobotName(robot);
var scene = robotComponent.webotsView.x3dScene;
if (robotComponent.billboardOrigin) {
robotComponent.billboardOrigin.parent.remove(robotComponent.billboardOrigin);
robotComponent.billboardOrigin = undefined;
}
for (var h = 0; h < robotComponent.highlightedAppearances.length; h++) {
var appearance = robotComponent.highlightedAppearances[h];
appearance.emissive.set(appearance.userData.initialEmissive);
}
robotComponent.highlightedAppearances = [];
scene.render();
}
function highlightX3DElement(robot, deviceElement) {
unhighlightX3DElement(robot);
var robotComponent = getRobotComponentByRobotName(robot);
var scene = robotComponent.webotsView.x3dScene;
var id = deviceElement.getAttribute('webots-transform-id');
var type = deviceElement.getAttribute('webots-type');
var object = scene.getObjectById(id, true);
if (object) {
// Show billboard origin.
var originBillboard = robotComponent.billboardOriginMesh.clone();
object.add(originBillboard);
robotComponent.billboardOrigin = originBillboard;
if (type === 'LED') {
var pbrIDs = deviceElement.getAttribute('ledPBRAppearanceIDs').split(' ');
for (var p = 0; p < pbrIDs.length; p++) {
var pbrID = pbrIDs[p];
if (pbrID) {
var ledColor = deviceElement.getAttribute('targetColor').split(' ');
ledColor = new THREE.Color(ledColor[0], ledColor[1], ledColor[2]);
object.traverse(function(child) {
if (child.material && child.material.name === pbrID) {
if (!child.material.userData.initialEmissive)
child.material.userData.initialEmissive = child.material.emissive.clone();
child.material.emissive.set(ledColor);
robotComponent.highlightedAppearances.push(child.material);
}
});
}
}
}
scene.render();
}
}
function setBillboardSize(robotComponent, scene) {
// Estimate roughly the robot scale based on the AABB.
var robotID = robotComponent.getAttribute('robot-node-id');
if (typeof robotID === 'undefined')
return;
var robot;
scene.traverse(function(object) {
if (object.isObject3D && object.name === robotID)
robot = object;
});
if (typeof robot === 'undefined')
return;
var aabb = new THREE.Box3().setFromObject(robot);
var max = Math.max(aabb.max.x - aabb.min.x, Math.max(aabb.max.y - aabb.min.y, aabb.max.z - aabb.min.z));
var size = Math.max(0.01, max) / 30.0;
robotComponent.billboardOriginMesh.geometry = new THREE.PlaneGeometry(size, size);
}
function getRobotComponentByRobotName(robotName) {
return document.querySelector('#' + robotName + '-robot-component');
}
function createRobotComponent(view) {
var robotComponents = document.querySelectorAll('.robot-component');
for (var c = 0; c < robotComponents.length; c++) { // foreach robot components of this page.
var robotComponent = robotComponents[c];
var webotsViewElement = document.querySelectorAll('.robot-webots-view')[0];
var robotName = webotsViewElement.getAttribute('id').replace('-robot-webots-view', '');
var webotsView = new webots.View(webotsViewElement);
robotComponent.webotsView = webotsView; // Store the Webots view in the DOM element for a simpler access.
webotsView.onready = function() { // When Webots View has been successfully loaded.
var camera = webotsView.x3dScene.getCamera();
// Make sure the billboard remains well oriented.
webotsView.x3dScene.preRender = function() {
if (robotComponent.billboardOrigin)
robotComponent.billboardOrigin.lookAt(camera.position);
};
robotComponent.highlightedAppearances = [];
// Store viewpoint.
camera.userData.initialQuaternion = camera.quaternion.clone();
camera.userData.initialPosition = camera.position.clone();
// Create the origin billboard mesh.
var loader = new THREE.TextureLoader();
var planeGeometry = new THREE.PlaneGeometry(0.05, 0.05);
var planeMaterial = new THREE.MeshBasicMaterial({
depthTest: false,
transparent: true,
opacity: 0.5,
map: loader.load(
computeTargetPath() + '../css/images/center.png'
)
});
robotComponent.billboardOriginMesh = new THREE.Mesh(planeGeometry, planeMaterial);
robotComponent.billboardOriginMesh.renderOrder = 1;
setBillboardSize(robotComponent, webotsView.x3dScene.scene);
};
// Load the robot X3D file.
webotsView.open(
computeTargetPath() + 'scenes/' + robotName + '/' + robotName + '.x3d',
undefined,
computeTargetPath() + 'scenes/' + robotName + '/'
);
// Load the robot meta JSON file.
$.ajax({
type: 'GET',
url: computeTargetPath() + 'scenes/' + robotName + '/' + robotName + '.meta.json',
dataType: 'text',
success: function(content) { // When successfully loaded.
// Populate the device component from the JSON file.
var deviceComponent = view.querySelector('#' + robotName + '-device-component');
var data = JSON.parse(content);
var categories = {};
robotComponent.setAttribute('robot-node-id', data['robotID']);
setBillboardSize(robotComponent, webotsView.x3dScene.scene);
if (data['devices'].length === 0)
toggleDeviceComponent(robotName);
for (var d = 0; d < data['devices'].length; d++) {
var device = data['devices'][d];
var deviceName = device['name'];
var deviceType = device['type'];
// Create or retrieve the device category container.
var category = null;
if (deviceType in categories)
category = categories[deviceType];
else {
category = document.createElement('div');
category.classList.add('device-category');
category.innerHTML = '<div class="device-title">' + deviceType + '</div>';
deviceComponent.appendChild(category);
categories[deviceType] = category;
}
// Create the new device.
var deviceDiv = document.createElement('div');
deviceDiv.classList.add('device');
deviceDiv.setAttribute('onmouseover', 'highlightX3DElement("' + robotName + '", this)');
deviceDiv.setAttribute('webots-type', deviceType);
deviceDiv.setAttribute('webots-transform-id', device['transformID']);
if ('transformOffset' in device) // The Device Transform has not been exported. The device is defined relatively to it's Transform parent.
deviceDiv.setAttribute('webots-transform-offset', device['transformOffset']);
deviceDiv.innerHTML = '<div class="device-name">' + deviceName + '</div>';
// Create the new motor.
if (deviceType.endsWith('Motor') && !device['track']) {
var minLabel = document.createElement('div');
minLabel.classList.add('motor-label');
var maxLabel = document.createElement('div');
maxLabel.classList.add('motor-label');
var slider = document.createElement('input');
slider.classList.add('motor-slider');
slider.setAttribute('type', 'range');
slider.setAttribute('step', 'any');
if (device['minPosition'] === device['maxPosition']) { // infinite range.
slider.setAttribute('min', -Math.PI);
slider.setAttribute('max', Math.PI);
minLabel.innerHTML = -3.14; // 2 decimals.
maxLabel.innerHTML = 3.14;
} else { // fixed range.
var epsilon = 0.000001; // To solve Windows browser bugs on slider when perfectly equals to 0.
slider.setAttribute('min', device['minPosition'] - epsilon);
slider.setAttribute('max', device['maxPosition'] + epsilon);
minLabel.innerHTML = Math.round(device['minPosition'] * 100) / 100; // 2 decimals.
maxLabel.innerHTML = Math.round(device['maxPosition'] * 100) / 100;
}
slider.setAttribute('value', device['position']);
slider.setAttribute('webots-position', device['position']);
slider.setAttribute('webots-transform-id', device['transformID']);
slider.setAttribute('webots-axis', device['axis']);
slider.setAttribute('webots-type', deviceType);
slider.addEventListener(isInternetExplorer() ? 'change' : 'input', function(e) {